實例講授Java並發編程之閉鎖。本站提示廣大學習愛好者:(實例講授Java並發編程之閉鎖)文章只能為提供參考,不一定能成為您想要的結果。以下是實例講授Java並發編程之閉鎖正文
閉鎖相當於一扇門,在閉鎖達到停止狀況之前,這扇門一向是封閉著的,沒有任何線程可以經由過程,當達到停止狀況時,這扇門才會翻開並允許一切線程經由過程。它可使一個或多個線程期待一組事宜產生。閉鎖狀況包含一個計數器,初始化為一個正式,負數表現須要期待的事宜數目。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 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