Java 同步计数器CountDownLatch
天飞 2017-12-21 17:46:56 浏览539 评论0摘要: 再次记得进阶方向:适用场景。
再次记得进阶方向:适用场景。

package demo.thread;
import java.util.concurrent.CountDownLatch;
public class ThreadMain {
public static void main(String[] args) throws Exception {
CountDownLatch latch = new CountDownLatch(3);
Worker worker1 = new Worker("Jack 程序员1", latch);
Worker worker2 = new Worker("Rose 程序员2", latch);
Worker worker3 = new Worker("Json 程序员3", latch);
worker1.start();
worker2.start();
worker3.start();
latch.await();
System.out.println("Main thread end!");
}
static class Worker extends Thread {
private String workerName;
private CountDownLatch latch;
public Worker(String workerName, CountDownLatch latch) {
this.workerName = workerName;
this.latch = latch;
}
@Override
public void run() {
try {
System.out.println("Worker: " + workerName + " is begin.");
Thread.sleep(1000L);
System.out.println("Worker: " + workerName + " is end.");
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
}
}
Worker: Rose 程序员2 is begin.
Worker: Json 程序员3 is begin.
Worker: Jack 程序员1 is begin.
Worker: Jack 程序员1 is end.
Worker: Rose 程序员2 is end.
Worker: Json 程序员3 is end.
Main thread end! 【云栖快讯】阿里云栖开发者沙龙(Java技术专场)火热来袭!快来报名参与吧! 详情请点击 评论 (0) 点赞 (0) 收藏 (0)
相关文章
- Java 线程同步组件 CountDownLatch 与…
- JDK5.0新特性系列---11.5.2线程 同步装置之…
- JDK5.0新特性系列---11.5.2线程 同步装置之…
- CountDownLatch
- 线程同步工具(三)等待多个并发事件完成
- java多线程 -- CountDownLatch 闭…
- java高并发之CountDownLatch,Cycli…
- 线程同步工具(三)等待多个并发事件完成
- Java中的阻塞队列(3)同步计数器
- java多线程系列:CountDownLatch