我正在学习JUC,我想计算程序用五个线程运行的总时间,但是它在打印“12,3”之后会被阻塞。请告诉我原因是什么?此外,如果我不调用函数"isPrime(int)",程序将正常执行。
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;
}
} 发布于 2017-07-08 15:03:05
您的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();
}
}https://stackoverflow.com/questions/44987268
复制相似问题