Java多线程CountDownLatch同步辅助类
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程CountDownLatch同步辅助类相关的知识,希望对你有一定的参考价值。
CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
主要方法:
public CountDownLatch(int count); //构造方法参数, 指定了计数的次数
public void countDown(); //调用此方法,则计数减一
public void await(); //调用此方法会一直阻塞当前线程,直到计时器的值为0
代码:
import java.util.concurrent.CountDownLatch; public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); new Worker(1, latch).run(); new Worker(2, latch).run(); new Worker(3, latch).run(); latch.await(); System.out.println("work down..."); } } class Worker extends Thread { private int i; private CountDownLatch latch; public Worker(int i, CountDownLatch latch) { this.i = i; this.latch = latch; } @Override public void run() { if(i == 3) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } latch.countDown(); System.out.println("worker " + i + "done..."); } }
本文出自 “架构师之路” 博客,请务必保留此出处http://lizhuquan0769.blog.51cto.com/2591147/1785491
以上是关于Java多线程CountDownLatch同步辅助类的主要内容,如果未能解决你的问题,请参考以下文章