线程池(newFixedThreadPool)、子线程回应(CountDownLatch)

原文地址:[url]http://blog.csdn.net/conquer0715/article/details/9000548[/url]
利用线程池newFixedThreadPool实现多线程,并通过CountDownLatch实现等待所有子线程结束后执行主线程。

//所有子线程执行完毕后执行主线程
static void threadsCall() {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
int threadTaskNum = 5;
final CountDownLatch answers = new CountDownLatch(threadTaskNum);//同步计数器
for (int i = 0; i < threadTaskNum; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println("线程" + Thread.currentThread().getName() + " 开始处理任务 ...");
Thread.sleep((long) (Math.random() * 5000));
System.out.println("线程" + Thread.currentThread().getName() + " 处理完毕,汇报结果!");
answers.countDown();
} catch (Exception e) {}
}
});
}
threadPool.shutdown();// 线程池不再接受新任务,全部任务结束后保证线程池退出运行
try {
answers.await();// 在所有子线程结束前保持阻塞
} catch (InterruptedException e) {}
System.out.println("线程" + Thread.currentThread().getName() + "已收到所有汇报结果");
}
结果:

线程pool-1-thread-1 开始处理任务 ...
线程pool-1-thread-2 开始处理任务 ...
线程pool-1-thread-3 开始处理任务 ...
线程pool-1-thread-4 开始处理任务 ...
线程pool-1-thread-5 开始处理任务 ...
线程pool-1-thread-5 处理完毕,汇报结果!
线程pool-1-thread-2 处理完毕,汇报结果!
线程pool-1-thread-3 处理完毕,汇报结果!
线程pool-1-thread-1 处理完毕,汇报结果!
线程pool-1-thread-4 处理完毕,汇报结果!
线程main已收到所有汇报结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值