Java - 使用Executors.newFixedThreadPool运行的线程永远不会完成

时间:2016-07-01 13:57:46

标签: java multithreading

我有线程应该完成,但没有那样做。每个线程中都有一个堆栈跟踪(使用调试器检查):

Unsafe.park(boolean, long) line: not available [native method]  
LockSupport.park(Object) line: not available    
AbstractQueuedSynchronizer$ConditionObject.await() line: not available  
LinkedBlockingQueue<E>.take() line: not available   
ThreadPoolExecutor.getTask() line: not available    
ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) line: not available 
ThreadPoolExecutor$Worker.run() line: not available 
Thread.run() line: not available    

代码:

ExecutorService threadExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
int totalNumberOfTasks = 0;
for(int i = 0; i < size; i++) {
    if(expr != null) {
        totalNumberOfTasks++;
        threadExecutor.execute(new Runnable() {

            @Override
            public void run() {
                doSmth();
            }
        });
    }
}
CountDownLatch latch = new CountDownLatch(totalNumberOfTasks);
try {
    latch.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}

我还尝试使用Semaphor代替CountDownLatch,但结果相同。有人能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

ExecutorService threadExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

// Must be available in Runnables
final CountDownLatch latch = new CountDownLatch(size);

int totalNumberOfTasks = 0;
for(int i = 0; i < size; i++) {
    if(expr != null) {
        totalNumberOfTasks++;
        threadExecutor.execute(new Runnable() {

            @Override
            public void run() {
                doSmth();
                latch.countDown(); // Countdown the latch
            }
        });
    }
}

try {
    latch.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}

如果您事先不知道任务数量,可以使用invokeAll

  

执行给定的任务,在完成所有任务后返回持有其状态和结果的Futures列表。

答案 1 :(得分:0)

当工作线程完成时,您缺少倒计时锁定。 我根本不会使用CountDownLatch,而是依靠ExecutorService的{​​{1}}和shutdown方法等待线程完成:< / p>

awaitTermination