Java 同步计数器CountDownLatch

  1. 云栖社区>
  2. 博客列表>
  3. 正文

Java 同步计数器CountDownLatch

天飞 2017-12-21 17:46:56 浏览3328 评论0

摘要: 再次记得进阶方向:适用场景。

再次记得进阶方向:适用场景。


3b2078bf4f5854469d7f60b1a92ab5748dfe7544

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技术专场)火热来袭!快来报名参与吧!  详情请点击

网友评论