CountDownLatch用法

CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。

CountDownLatch类只提供了一个构造器:

1

public CountDownLatch(int count) {  };  //参数count为计数值

然后下面这3个方法是CountDownLatch类中最重要的方法:

1

2

3

public void await() throws InterruptedException { };   //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行

public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };  //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行

public void countDown() { };  //将count值减1

下面看一个例子大家就清楚CountDownLatch的用法了:

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

public class Test {

     public static void main(String[] args) {  

         final CountDownLatch latch = new CountDownLatch(2);

 

         new Thread(){

             public void run() {

                 try {

                     System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");

                    Thread.sleep(3000);

                    System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");

                    latch.countDown();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

             };

         }.start();

 

         new Thread(){

             public void run() {

                 try {

                     System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");

                     Thread.sleep(3000);

                     System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");

                     latch.countDown();

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

             };

         }.start();

 

         try {

             System.out.println("等待2个子线程执行完毕...");

            latch.await();

            System.out.println("2个子线程已经执行完毕");

            System.out.println("继续执行主线程");

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

     }

}

执行结果:

1

2

3

4

5

6

7

线程Thread-0正在执行

线程Thread-1正在执行

等待2个子线程执行完毕...

线程Thread-0执行完毕

线程Thread-1执行完毕

2个子线程已经执行完毕

继续执行主线程

 

 

例子2:

package com.unicss;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class TestCountDownLatch {
	public static void main(String[] args) throws InterruptedException {
		// 开始的倒数锁
		final CountDownLatch begin = new CountDownLatch(1);
		// 结束的倒数锁
		final CountDownLatch end = new CountDownLatch(10);
		// 十名选手
		final ExecutorService exec = Executors.newFixedThreadPool(10);

		for (int index = 0; index < 10; index++) {
			final int NO = index + 1;
			Runnable run = new Runnable() {
				public void run() {
					try {
						begin.await();// 一直阻塞
						Thread.sleep((long) (Math.random() * 10000));
						System.out.println("No." + NO + " arrived");
					} catch (InterruptedException e) {
					} finally {
						end.countDown();
					}
				}
			};
			exec.submit(run);
		}
		System.out.println("Game Start");
		begin.countDown();
		end.await();
		System.out.println("Game Over");
		exec.shutdown();
	}
}

 

执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值