2017-07-08 7 views
1

私はJUCを学んでいます。プログラムが5つのスレッドで実行される合計時間を計算したいのですが、 "1 2 3"その理由を教えてください。 さらに、関数 "isPrime(int)"を呼び出さないと、プログラムは正常に実行されます。それは4に遭遇した場合、そのプライムとは、したがって、プライムされていないとき私は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をインクリメントされていない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

マート、それは馬鹿ではない、私たちはすべてそれをしてくれたことを信じてください。私はそこで使うことができると大歓迎です –

関連する問題