CountDownLatch实现主线程等待所有子线程运行结束后再继续执行的实现
来源:互联网 发布:气象站点数据下载 编辑:程序博客网 时间:2024/05/21 19:22
使用CountDownLatch实现主线程等待所有子线程运行结束后再继续执行的实现。随手写的例子很简单,做个备份吧。
A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch
is initialized with a given count. The await
methods block until the current count reaches zero due to invocations of the countDown()
method, after which all waiting threads are released and any subsequent invocations of await
return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier
.
A CountDownLatch
is a versatile synchronization tool and can be used for a number of purposes. A CountDownLatch
initialized with a count of one serves as a simple on/off latch, or gate: all threads invoking await
wait at the gate until it is opened by a thread invoking countDown()
. A CountDownLatch
initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.
A useful property of a CountDownLatch
is that it doesn't require that threads calling countDown
wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past an await
until all threads could pass.
public class TestCountDownLatch {private static CountDownLatch latch;public static void main(String[] args) throws InterruptedException {latch = new CountDownLatch(10);for (int i = 0; i < 10; i++) {new Thread(new MyRunnable(i)).start();}System.out.println("main thread begin to await util all the thread finished");latch.await();System.out.println("main thread is over");}static class MyRunnable implements Runnable {int num;public MyRunnable(int num) {this.num = num;}@Overridepublic void run() {System.out.println("Thread " + num + " run");try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} finally {latch.countDown();System.out.println("Thread " + num + " latch countDown");}}}}
- CountDownLatch实现主线程等待所有子线程运行结束后再继续执行的实现
- 多个子线程并发执行,主线程等待所有子线程都结束后再继续运行
- 主线程等待子线程执行结束后再执行的实现方式
- 主线程等待所有子线程执行完毕后再继续的问题
- 多线程中主线程等待所有子线程执行完再继续执行的解决方法
- 主线程等待所有子线程完成后再执行
- 用CountDownLatch实现主线程等待子线程
- 主线程等待子线程执行结束
- java线程池主线程等待子线程执行完成后再继续处理后面工作
- java线程池主线程等待子线程执行完成后再继续处理后面工作
- java并发编程:主线程等待子线程结束 CountDownLatch
- 主线程等待子线程执行完毕后再执行
- 等待主线程结束后继续执行余下代码,
- Java主线程等待子线程执行完毕-CountDownLatch
- Java主线程等待子线程执行完毕-CountDownLatch
- Java主线程等待子线程执行完毕-CountDownLatch
- 并发问题和主线程等待所有子线程运行完毕再执行
- 主线程中使用join等待所有子线程执行结束
- Java线程之守护线程(Daemon)
- 当博客都不给链接以后
- [原创]如何提供C++到lua的接口
- python 时间
- Android app 使用webview
- CountDownLatch实现主线程等待所有子线程运行结束后再继续执行的实现
- 基于单片机的电子密码锁的实现
- 关于MongoDB的group分组
- 查找问题整理(2)查找第K大的数Kth Order Statitic
- hdu 1754
- 随便写写
- 7个高级技巧帮助你释放大量Mac OS X硬盘空间
- Lucene的多域查询、结果中查询、查询结果分页、高亮查询结果和结果评分
- 基于单片机的生日快乐歌