我正在学习JUC,我想计算程序运行五个线程的总时间,但是打印“1 2 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;
}
}
最佳答案
您的Runnable
运行方法仅在其素数时递增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();
}
}
关于java - 我正在使用 JUC 的 CountDownLatch,但我的应用程序被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44987268/