Java并发编程之栅栏(CyclicBarrier)实例介绍
栅栏类似闭锁,但是它们是有区别的.
1.闭锁用来等待事件,而栅栏用于等待其他线程.什么意思呢?就是说闭锁用来等待的事件就是countdown事件,只有该countdown事件执行后所有之前在等待的线程才有可能继续执行;而栅栏没有类似countdown事件控制线程的执行,只有线程的await方法能控制等待的线程执行.
2.cyclicbarrier强调的是n个线程,大家相互等待,只要有一个没完成,所有人都得等着。
场景分析:10个人去春游,规定达到一个地点后才能继续前行.代码如下
import java.util.concurrent.brokenbarrierexception;
import java.util.concurrent.cyclicbarrier;
class cyclicbarrierworker implements runnable {
private int id;
private cyclicbarrier barrier;
public cyclicbarrierworker(int id, final cyclicbarrier barrier) {
this.id = id;
this.barrier = barrier;
}
@override
public void run() {
// todo auto-generated method stub
try {
system.out.println(id + " th people wait");
barrier.await(); // 大家等待最后一个线程到达
} catch (interruptedexception | brokenbarrierexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
public class testcyclicbarrier {
public static void main(string[] args) {
int num = 10;
cyclicbarrier barrier = new cyclicbarrier(num, new runnable() {
@override
public void run() {
// todo auto-generated method stub
system.out.println("go on together!");
}
});
for (int i = 1; i <= num; i++) {
new thread(new cyclicbarrierworker(i, barrier)).start();
}
}
}
输出
1 th people wait
2 th people wait
3 th people wait
4 th people wait
5 th people wait
7 th people wait
8 th people wait
6 th people wait
9 th people wait
10 th people wait
go on together!
上一篇: Java利用三目运算符比较三个数字的大小
下一篇: php实用代码片段整理