转载

线程同步辅助类CountDownLatch

《线程同步辅助类CountDownLatch》

Java5提供了一个非常有用的线程同步辅助类型,java.util.concurrent.CountDownLatch。假设有多个线程正在执行异步操作,主线程希望这些异步线程全部完成之后再继续执行后续任务,那么使用CountDownLatch将非常方便。当这些异步任务并未全部执行完成之前,主线程会一直阻塞,直至所有的异步任务完成为止。

示例代码,如下所示:

public class ThreadTest {  public static void main(String[] args) {   final CountDownLatch countDownLatch = new CountDownLatch(2);   System.out.println("befor count->" + countDownLatch.getCount());   new Thread() {    public void run() {     System.out.println("线程A准备开始工作...");     try {      Thread.sleep(1000);     } catch (InterruptedException e) {      e.printStackTrace();     }     System.out.println("线程A工作完成...");     countDownLatch.countDown();    }   }.start();   new Thread() {    public void run() {     System.out.println("线程B准备开始工作...");     try {      Thread.sleep(5000);     } catch (InterruptedException e) {      e.printStackTrace();     }     System.out.println("线程B工作完成...");     countDownLatch.countDown();    }   }.start();   try {    countDownLatch.await();    System.out.println("after count->" + countDownLatch.getCount());    System.out.println("所有线程全部工作完成...");   } catch (InterruptedException e) {    e.printStackTrace();   }   } }
原文  http://itindex.net/detail/55149-线程-同步-countdownlatch
正文到此结束
Loading...