Java并發編程之閉鎖簡介

jopen 9年前發布 | 12K 次閱讀 Java開發 java并發

閉鎖相當于一扇門,在閉鎖到達結束狀態之前,這扇門一直是關閉著的,沒有任何線程可以通過,當到達結束狀態時,這扇門才會打開并容許所有線程通過。它可以使一個或多個線程等待一組事件發生。閉鎖狀態包括一個計數器,初始化為一個正式,正數表示需要等待的事件數量。countDown方法遞減計數器,表示一個事件已經發生,而await方法等待計數器到達0,表示等待的事件已經發生。CountDownLatch強調的是一個線程(或多個)需要等待另外的n個線程干完某件事情之后才能繼續執行。

     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));
}
}
}</pre><br />


輸出

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
</div>
來自:http://blog.csdn.net/csujiangyu/article/details/44236205

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!