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;
}
}
謝謝,朋友,我太蠢! – ligen
伴侶,這不是愚蠢的,相信我,我們都做到了。我很受歡迎,我可以在那裏使用 –