Java 同步计数器CountDownLatch

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


Java 同步计数器CountDownLatch

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!


上一篇:SPRING01_基于gradle6.8.2和JDK15搭建Spring源码坏境(三)


下一篇:容器花絮:什么时候应该将应用程序切分为多个容器?