Java並發編程之柵欄(CyclicBarrier)實例引見。本站提示廣大學習愛好者:(Java並發編程之柵欄(CyclicBarrier)實例引見)文章只能為提供參考,不一定能成為您想要的結果。以下是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!