實例講解Java并發(fā)編程之閉鎖
閉鎖相當(dāng)于一扇門,在閉鎖到達(dá)結(jié)束狀態(tài)之前,這扇門一直是關(guān)閉著的,沒有任何線程可以通過,當(dāng)?shù)竭_(dá)結(jié)束狀態(tài)時,這扇門才會打開并容許所有線程通過。它可以使一個或多個線程等待一組事件發(fā)生。閉鎖狀態(tài)包括一個計數(shù)器,初始化為一個正式,正數(shù)表示需要等待的事件數(shù)量。countDown方法遞減計數(shù)器,表示一個事件已經(jīng)發(fā)生,而await方法等待計數(shù)器到達(dá)0,表示等待的事件已經(jīng)發(fā)生。CountDownLatch強(qiáng)調(diào)的是一個線程(或多個)需要等待另外的n個線程干完某件事情之后才能繼續(xù)執(zhí)行。
場景應(yīng)用:
10個運動員準(zhǔn)備賽跑,他們等待裁判一聲令下就開始同時跑,當(dāng)最后一個人通過終點的時候,比賽結(jié)束。10個運動相當(dāng)于10個線程,這里關(guān)鍵是控制10個線程同時跑起來,還有怎么判斷最后一個線程到達(dá)終點??梢杂?個閉鎖,第一個閉鎖用來控制10個線程等待裁判的命令,第二個閉鎖控制比賽結(jié)束。
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(); //準(zhǔn)備就緒 } catch (InterruptedException e) { e.printStackTrace(); } finally { end.countDown(); //計數(shù)器減一,到達(dá)終點 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(); //等待結(jié)束 } 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
相關(guān)文章
SpringCloud-Spring?Boot?Starter使用測試及問題小結(jié)
Spring?Boot?Starter?是在?SpringBoot?組件中被提出來的一種概念、簡化了很多煩瑣的配置、通過引入各種?Spring?Boot?Starter?包可以快速搭建出一個項目的腳手架,這篇文章主要介紹了SpringCloud-Spring?Boot?Starter使用測試,需要的朋友可以參考下2022-07-07Spring Cloud微服務(wù)架構(gòu)的構(gòu)建:分布式配置中心(加密解密功能)
這篇文章主要給大家介紹了關(guān)于Spring Cloud微服務(wù)架構(gòu)的構(gòu)建:分布式配置中心(加密解密)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2018-05-05通過實例了解java checked和unchecked異常
這篇文章主要介紹了通過實例了解checked和unchecked異常,Java異常分為兩種類型,checked異常和unchecked異常,另一種叫法是異常和錯誤。下面小編就帶大家來一起學(xué)習(xí)一下吧2019-06-06