java多线程-CountDownLatch
Posted liuboyuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程-CountDownLatch相关的知识,希望对你有一定的参考价值。
CountDownLatch
主要方法:
public void await() throws InterruptedException ; //调用后线程阻塞,直到count减为0 public boolean await(long timeout, TimeUnit unit) throws InterruptedException ; //有超时的await,超时时间到到达后,线程不再阻塞继续执行,可中断 public void countDown() ; //将count值减1
应用:
//子服务 class Server implements Runnable { private String name; private CountDownLatch latch; Server(String name, CountDownLatch latch){ this.name = name; this.latch = latch; } @Override public void run() { try{ start(); System.out.println(name +":start over"); }finally { latch.countDown(); } } private void start() { try { System.out.println(name+":start"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } //主服务 class MainServer implements Runnable { private CountDownLatch latch; MainServer(CountDownLatch latch){ this.latch = latch; } @Override public void run() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("MainServer start"); } }
public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); Server server1 = new Server("Server a",countDownLatch); Server server2 = new Server("Server b",countDownLatch); Server server3 = new Server("Server c",countDownLatch); MainServer mainServer = new MainServer(countDownLatch); new Thread(server1).start(); new Thread(server2).start(); new Thread(server3).start(); new Thread(mainServer).start(); }
结果:
Server a:start
Server c:start
Server b:start
Server a:start over
Server c:start over
Server b:start over
MainServer start
上例中模拟一个主服务和3个子服务启动,主服务的启动依赖子服务启动,只有当3个子服务都启动完成后主服务才会执行启动。
要点:
- 一个CountDownLatch对象只能使用一次,无法重复使用。
- latch.countDown(); 建议放到finally语句里,countDown是原子操作。
以上是关于java多线程-CountDownLatch的主要内容,如果未能解决你的问题,请参考以下文章
Java并发多线程编程——并发工具类CountDownLatch(线程计数器)
java 多线程 27 :多线程组件之CountDownLatch
Java多线程-两种常用的线程计数器CountDownLatch和循环屏障CyclicBarrier