java - 如何获知new Runnable(){run(){}}中的逻辑执行完毕?
大家讲道理
大家讲道理 2017-04-18 10:01:57
0
2
522

如何知道写在runnable()中的逻辑执行完毕??

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
巴扎黑
ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
    es.execute(new Runnable() { /*  your task */ });
es.shutdown();
try{
    //等待线程执行完毕
    boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES);
    if (finished){
        //do something
    }
}catch(InterruptedException e){
    //timeout
}

Original answer on StackOverflow.

刘奇
boolean awaitTermination(long timeout,TimeUnit unit)throws InterruptedException

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.  

The assumption here is that all tasks will be executed within 1 minute. If the scenario is met, this is the simplest.
If the execution may not be successful within the timeout period, or the execution time cannot be evaluated.
Is it more convenient to use this class?

java.util.concurrent.CountDownLatch 

There may be many methods, and the one that suits the scene is the best.
The other answers in the original stackoverflow answer posted upstairs are also of reference value

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template