2017-07-08 52 views
1

我正在學習JUC,我想計算程序以五個線程運行的總時間,但它在打印「1 2 3」後被阻止。告訴我是什麼原因? 另外,如果我不調用函數「isPrime(int)」,程序將正常執行。我正在使用JUC的CountDownLatch,但我的應用程序被阻止

public class TestCountDownLatch { 

public static void main(String[] args) { 
    CountDownLatch cwt = new CountDownLatch(5); 
    Runnable runnable = new CountDownThread(cwt); 
    long start = System.currentTimeMillis(); 
    for (int i = 0; i < 5; i++) { 
     new Thread(runnable).start(); 
    } 
    try { 
     cwt.await(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
    long end = System.currentTimeMillis(); 
    System.out.println("total time :" + (end - start)); 
    } 
} 



class CountDownThread implements Runnable{ 

private CountDownLatch countdownLatch; 

private int num = 1; 

public CountDownThread(CountDownLatch countdownLatch) { 
    this.countdownLatch = countdownLatch; 
} 


@Override 
public void run() { 
    try{ 
     while(true){ 
      synchronized (this) { 
       if(num > 100){ 
        break; 
       } 
       if(isPrime(num)){ 
        System.out.println(num++); 
       } 
      } 
     } 
    }finally{ 
     countdownLatch.countDown(); 
    } 

} 


private boolean isPrime(int i) { 
    for (int j = 2; j <= (i >> 1); j++) { 
     if(i % j == 0){ 
      return false; 
     } 
    } 
    return true; 
} 
} 

回答

0

Runnable run方法,只增加num當其首要,因此當它遇到4這不是素數它不是遞增num和你的程序是在這種狀態下,當其運行期間的休息。擺弄下面提到的那部分,這使得它超越了這一點,並打破了100

@Override 
public void run() { 
    try { 
     while (true) { 
      synchronized (this) { 
       num++; // initially assigning int num = 0, and then doing this 
       if (num > 100) { 
        break; 
       } 
       if (isPrime(num)) { 
        System.out.println(num); 
       } 
      } 
     } 
    } finally { 
     countdownLatch.countDown(); 
    } 
} 
+0

謝謝,朋友,我太蠢! – ligen

+0

伴侶,這不是愚蠢的,相信我,我們都做到了。我很受歡迎,我可以在那裏使用 –

相關問題