多线程之CountDownLatch对象

概念

CountDownLatch是通过一个计数器来实现的,计数器的初始值为线程的数量。每当一个线程完成了自己的任务后,计数器的值就会减1。当计数器值到达0时,它表示所有的线程已经完成了任务,然后在闭锁上等待的线程就可以恢复执行任务。
构造器中的计数值(count)实际上就是闭锁需要等待的线程数量。这个值只能被设置一次,而且CountDownLatch没有提供任何机制去重新设置这个计数值。

与CountDownLatch的第一次交互是主线程等待其他线程。主线程必须在启动其他线程后立即调用CountDownLatch.await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。

其他N个线程必须引用闭锁对象,因为他们需要通知CountDownLatch对象,他们已经完成了各自的任务。这种通知机制是通过 CountDownLatch.countDown()方法来完成的;每调用一次这个方法,在构造函数中初始化的count值就减1。所以当N个线程都调 用了这个方法,count的值等于0,然后主线程就能通过await()方法,恢复执行自己的任务。


await()和countDown()

示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.example.demo.three.untils.countdownlouch;
 
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
/**
  * 案例:
  * 取到一批数据,利用两个线程对数据进行逻辑处理
  * 当处理完过后,再用这批数据做一些其它事情
  */
public class CountDownLunchTest1 {
     private static Random random = new Random(System.currentTimeMillis());
     private static ExecutorService executor = Executors.newFixedThreadPool( 2 );
     private static CountDownLatch latch = new CountDownLatch( 9 );
 
     public static void main(String[] args) throws InterruptedException {
         //获取数组
         int [] data = query();
         //两次线程去操作逻辑
         for ( int i = 0 ; i < data.length; i++) {
             executor.execute( new SimpleRunnAble(data, i, latch));
 
         }
         //保证所有线程执行完毕,再执行下面程序
         latch.await();
         executor.shutdown();
         //获取处理过的数据
         System.out.println( "取到数字" + Arrays.toString(data));
     }
 
     static class SimpleRunnAble implements Runnable {
         private final int [] data;
         private final int index;
         private final CountDownLatch latch;
 
         SimpleRunnAble( int [] data, int index, CountDownLatch latch) {
             this .data = data;
             this .index = index;
             this .latch = latch;
         }
 
         @Override
         public void run() {
             try {
                 Thread.sleep(random.nextInt( 1000 ));
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
 
             int value = data[index];
             if (value % 2 == 0 ) {
                 data[index] = value * 2 ;
             } else {
                 data[index] = value * 10 ;
             }
             System.out.println(Thread.currentThread().getName() + "结束" );
             latch.countDown();
         }
     }
 
     private static int [] query() {
         return new int []{ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };
     }
}

await(long timeout, TimeUnit unit)

await(long timeout, TimeUnit unit):表示等待最长时间。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.example.demo.three.untils.countdownlouch;
 
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLunchTest2 {
     public static void main(String[] args) throws InterruptedException {
         //new CountDownLatch(0)当为0时,latch.await()无效果
         CountDownLatch latch = new CountDownLatch( 1 );
         new Thread() {
             @Override
             public void run() {
                 try {
                     Thread.sleep( 1000 );
                     latch.countDown();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         }.start();
         /**
          * 最多等待10秒
          * 1.如果10秒内,没有countDown为0,10秒后发行
          * 2.如果10秒内,countDown为0,立刻发行,不用等待10秒
          */
         latch.await( 10 ,TimeUnit.SECONDS);
         System.out.println( "==========" );
     }
}

转自:https://www.2cto.com/kf/201710/688656.html

猜你喜欢

转载自blog.csdn.net/simon_it/article/details/79870698