使用场景,在多线程执行完成后根据多线程执行返回值继续后续操作。
代码如下
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
private final static ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main(String[] args) {
final List<Integer> resultList = Collections.synchronizedList(new ArrayList<Integer>());
int num = 100;
final CountDownLatch latch = new CountDownLatch(num);
do {
final int current = num;
executor.execute(new Runnable() {
@Override
public void run() {
resultList.add(doSomeThing(current));
System.out.println(Thread.currentThread().getName()+":"+current);
latch.countDown(); //减减操作
}
});
num--;
}while(num > 0);
try {
latch.await(1,TimeUnit.MINUTES); //挂起状态,latch的count为0才会往后执行
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("=====多线程任务执行完毕========");
resultList.forEach(it->{
System.out.println(it);
});
}
private static int doSomeThing(int num) {
try {
Thread.sleep(200); //模拟耗时业务
} catch (InterruptedException e) {
e.printStackTrace();
}
return num;
}
}
执行结果:
pool-1-thread-1:100
pool-1-thread-5:96
pool-1-thread-8:93
...
=====多线程任务执行完毕========
100
99
97
....
省略掉一部分输出
网友评论