首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我正在使用JUC的CountDownLatch,但是我的应用程序被屏蔽了

我正在使用JUC的CountDownLatch,但是我的应用程序被屏蔽了
EN

Stack Overflow用户
提问于 2017-07-08 14:25:46
回答 1查看 56关注 0票数 1

我正在学习JUC,我想计算程序用五个线程运行的总时间,但是它在打印“12,3”之后会被阻塞。请告诉我原因是什么?此外,如果我不调用函数"isPrime(int)",程序将正常执行。

代码语言:javascript
复制
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;
}
}   
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-08 15:03:05

您的Runnable run方法,只在它的素数时递增num,因此当它遇到非素数的4时,它不递增num,而您的程序在运行时的剩余时间处于这种状态。摆弄下面提到的部分,这使它超越了这个点,并在100中断。

代码语言:javascript
复制
 @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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44987268

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档