java - 我正在使用 JUC 的 CountDownLatch,但我的应用程序被阻止

标签 java

我正在学习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/

相关文章:

java - 对扩展现有枚举类型的泛型感到困惑

java - OrientDB SQL 连接替代方案

java - 以格式 HH :MM:SS 连续减少 java 中的时间

java - 使用 DataProvider 的 TestNG 会跳过所有测试

java - Java Char 数组有什么用?

java - WebappClassLoader 间歇性地需要 12 秒来加载本地 JAR 文件

java - 在 Java 中用正则表达式剥离和替换文本字符串

java - 错误 : cannot find symbol, 声明了对象,但看不到公共(public)变量

java - 改造:Unable to create adapter

java - 输入 editText 超过 10 位时应用程序停止