赞助

java并发编程CountDownLatch

 1 /**
 2      * CountDownLatch用法
 3      * CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,
 4      * 它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了
 5      */
 6     @Test
 7     public void getThread(){
 8         final CountDownLatch latch = new CountDownLatch(2);
 9         new Thread (){
10             @Override
11             public void run() {
12                 try {
13                     System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
14                     Thread.sleep(3000);
15                     System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
16                     latch.countDown();
17                     System.out.println(latch);
18                 }catch (InterruptedException e){
19                     e.printStackTrace();
20                 }
21             }
22         }.start();
23         new Thread (){
24             @Override
25             public void run() {
26                 try {
27                     System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");
28                     Thread.sleep(3000);
29                     System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");
30                     latch.countDown();
31                     System.out.println(latch);
32                 }catch (InterruptedException e){
33                     e.printStackTrace();
34                 }
35             }
36         }.start();
37 
38         try {
39             System.out.println("等待2个子线程执行完毕...");
40             latch.await();
41             System.out.println("2个子线程已经执行完毕");
42             System.out.println("继续执行主线程");
43         }catch(InterruptedException e){
44             e.printStackTrace();
45         }
46     }

posted @ 2018-07-04 13:43  念念不忘、  阅读(204)  评论(0编辑  收藏  举报