執行個體講解Java並發編程之閉鎖_java

來源:互聯網
上載者:User

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

情境應用:
10個運動員準備賽跑,他們等待裁判一聲令下就開始同時跑,當最後一個人通過終點的時候,比賽結束。10個運動相當於10個線程,這裡關鍵是控制10個線程同時跑起來,還有怎麼判斷最後一個線程到達終點。可以用2個閉鎖,第一個閉鎖用來控制10個線程等待裁判的命令,第二個閉鎖控制比賽結束。

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)); } }}

輸出

1th people is ready2th people is ready4th people is ready6th people is ready3th people is ready10th people is ready8th people is ready5th people is ready7th people is ready9th people is readyjudge say : run !1th people arrive4th people arrive10th people arrive5th people arrive2th people arrivejudge say : all arrived !9th people arrive7th people arrive8th people arrive3th people arrive6th people arrivespend time: 970933

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.