程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 同步輔助類CountDownLatch用法,countdownlatch用法

同步輔助類CountDownLatch用法,countdownlatch用法

編輯:JAVA綜合教程

同步輔助類CountDownLatch用法,countdownlatch用法


  CountDownLatch是一個同步輔助類,猶如倒計時計數器,創建對象時通過構造方法設置初始值,調用CountDownLatch對象的await()方法則使當前線程處於等待狀態,調用countDown()方法就將計數器減1,當計數到達0時,則所有等待線程全部開始執行。它提供的常用方法:

 public CountDownLatch(int count);   //構造方法參數指定了計數的次數

 public void countDown();           //當前線程調用此方法,則計數減一

 public void await() throws InterruptedException;   //調用此方法會一直阻塞當前線程,直到計時器的值為0

使用方式如下:

package basic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestCountDown {

    private static final int PLAYER_AMOUNT = 5;

    public static void main(String[] args) {
        /* 對於每位運動員,CountDownLatch減1後即開始比賽 */
        CountDownLatch begin = new CountDownLatch(1);
        /* 對於整個比賽,所有運動員結束後才算結束 */
        CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
        Player[] players = new Player[PLAYER_AMOUNT];
        for (int i = 0; i < PLAYER_AMOUNT; i++) {
            players[i] = new Player(i + 1, begin, end);
        }
        /* 設置特定的線程池,大小為5 */
        ExecutorService executorService = Executors.newFixedThreadPool(PLAYER_AMOUNT);
        for (Player player : players) {
            /* 分配線程 */
            executorService.execute(player);
        }
        System.out.println("Race begins!");
        /* 所有Player等待 比賽信號的開始 */
        begin.countDown();
        try {
            /* 等待end狀態變為0,即為比賽結束 */
            end.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Race ends!");
        }
        executorService.shutdown();
    }
}

class Player implements Runnable {

    private final int            id;
    private final CountDownLatch begin;
    private final CountDownLatch end;

    public Player(int id, CountDownLatch begin, CountDownLatch end){
        super();
        this.id = id;
        this.begin = begin;
        this.end = end;
    }

    @Override
    public void run() {
        try {
            /* 等待begin的狀態為0 */
            begin.await();
            /* 隨機分配時間,即運動員完成時間 */
            Thread.sleep((long) (Math.random() * 100));
            System.out.println("Play" + id + "arrived.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            /* 使end狀態減1,當前線程的運動員完成比賽 */
            end.countDown();
        }
    }

}

代碼中begin.countDown()是比賽信號開始,五個begin.await()的線程開始執行,執行完之後在finally塊中執行end.countDown(),當計數器減為0的時候,喚醒main方法中的end.await(),程序接著往下執行,打印比賽結束。

Causes the current thread to wait until the latch has counted down to zero, unless the thread is interrupted. If the current count is zero then this method returns immediately. If the current count is greater than zero then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happen:   1.The count reaches zero due to invocations of the countDown() method; or   2.Some other thread interrupts the current thread.

If the current thread: has its interrupted status set on entry to this method; or is interrupted while waiting, then java.lang.InterruptedException is thrown and the current thread's interrupted status is cleared. Throws: java.lang.InterruptedException if the current thread is interrupted while waiting public void await() throws InterruptedException {   sync.acquireSharedInterruptibly(1); }

上面是核心方法await()的JDK源碼!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved