CountDownLatch相关API

java线程基础之CountDownLatch学习

JDK相关解释

一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier

下面是一个Demo 


package test.Threae;


import java.util.concurrent.CountDownLatch;
/**
 * 
 * @author wzn
 * 
 */
public class CountDownLatchDemo {

static CountDownLatch downLatch = new CountDownLatch(2);
public static void main(String[] args) {
new Thread(new Workers("worker1",downLatch, 5000)).start();
new Thread(new Workers("worker2",downLatch, 8000)).start();
try {
downLatch.await();
System.out.println("work over ");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


class Workers implements Runnable{
private final String workerName;
private final CountDownLatch downLatch;
private final int time;
public Workers(String workerName, CountDownLatch downLatch,int time){
this.downLatch= downLatch;
this.time = time;
this.workerName= workerName;
}
@Override
public void run() {
System.out.println(workerName+"work start");
doWorking();
System.out.println(workerName+"work end bye");
downLatch.countDown();
}


private void doWorking() {
System.out.println("do working");
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

java线程基础之CountDownLatch学习

也就是说主线程在等待所有其它的子线程完成后再往下执行

相关文章:

  • 2018-01-22
  • 2022-03-07
  • 2021-12-08
  • 2021-09-12
  • 2021-09-29
  • 2021-10-14
  • 2021-09-21
  • 2021-11-23
猜你喜欢
  • 2021-06-28
  • 2021-08-31
  • 2021-07-23
  • 2021-11-23
  • 2021-11-24
  • 2021-04-10
相关资源
相似解决方案