服务器之家

服务器之家 > 正文

实例讲解Java并发编程之闭锁

时间:2019-12-16 13:17     来源/作者:junjie

闭锁相当于一扇门,在闭锁到达结束状态之前,这扇门一直是关闭着的,没有任何线程可以通过,当到达结束状态时,这扇门才会打开并容许所有线程通过。它可以使一个或多个线程等待一组事件发生。闭锁状态包括一个计数器,初始化为一个正式,正数表示需要等待的事件数量。countDown方法递减计数器,表示一个事件已经发生,而await方法等待计数器到达0,表示等待的事件已经发生。CountDownLatch强调的是一个线程(或多个)需要等待另外的n个线程干完某件事情之后才能继续执行。

场景应用:
10个运动员准备赛跑,他们等待裁判一声令下就开始同时跑,当最后一个人通过终点的时候,比赛结束。10个运动相当于10个线程,这里关键是控制10个线程同时跑起来,还有怎么判断最后一个线程到达终点。可以用2个闭锁,第一个闭锁用来控制10个线程等待裁判的命令,第二个闭锁控制比赛结束。

?
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
import java.util.concurrent.CountDownLatch;
 
class Aworker implements Runnable {
 private int num;
 private CountDownLatch begin;
 private CountDownLatch end;
 
 public Aworker(int num, final CountDownLatch begin, final CountDownLatch end) {
 this.num = num;
 this.begin = begin;
 this.end = end;
 }
 
 @Override
 public void run() {
 // TODO Auto-generated method stub
 try {
  System.out.println(num + "th people is ready");
  begin.await();  //准备就绪
 } catch (InterruptedException e) {
  e.printStackTrace();
 } finally {
  end.countDown();  //计数器减一,到达终点
  System.out.println(num + "th people arrive");
 }
 }
}
 
public class Race {
 public static void main(String[] args) {
 int num = 10;
 CountDownLatch begin = new CountDownLatch(1);
 CountDownLatch end = new CountDownLatch(num);
 
 for (int i = 1; i <= num; i++) {
  new Thread(new Aworker(i, begin, end)).start();
 }
 
 try {
  Thread.sleep((long) (Math.random() * 5000));
 } catch (InterruptedException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 }
 System.out.println("judge say : run !");
 begin.countDown(); //裁判一声令下开始跑
 long startTime = System.nanoTime();
 try {
  end.await(); //等待结束
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } finally {
  long endTime = System.nanoTime();
  System.out.println("judge say : all arrived !");
  System.out.println("spend time: " + (endTime - startTime));
 }
 }
}

输出

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1th people is ready
2th people is ready
4th people is ready
6th people is ready
3th people is ready
10th people is ready
8th people is ready
5th people is ready
7th people is ready
9th people is ready
judge say : run !
1th people arrive
4th people arrive
10th people arrive
5th people arrive
2th people arrive
judge say : all arrived !
9th people arrive
7th people arrive
8th people arrive
3th people arrive
6th people arrive
spend time: 970933
标签:

相关文章

热门资讯

玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分
玄元剑仙肉身有什么用 玄元剑仙肉身境界等级划分 2019-06-21
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
配置IIS网站web服务器的安全策略配置解决方案
配置IIS网站web服务器的安全策略配置解决方案 2019-05-23
Nginx服务器究竟是怎么执行PHP项目
Nginx服务器究竟是怎么执行PHP项目 2019-05-24
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情
华为nova5pro和p30pro哪个好 华为nova5pro和华为p30pro对比详情 2019-06-22
返回顶部