JAVA柵欄和閉鎖的區別


  閉鎖:一個同步輔助類,在完成一組正在其他線程中執行的操作之前,它允許一個或多個線程一直等待。即,一組線程等待某一事件發生,事件沒有發生前,所有線程將阻塞等待;而事件發生后,所有線程將開始執行;閉鎖最初處於封閉狀態,當事件發生后閉鎖將被打開,一旦打開,閉鎖將永遠處於打開狀態。

  閉鎖CountDownLatch唯一的構造方法CountDownLatch(int count),當在閉鎖上調用countDown()方法時,閉鎖的計數器將減1,當閉鎖計數器為0時,閉鎖將打開,所有線程將通過閉鎖開始執行。

  柵欄:一個同步輔助類,它允許一組線程互相等待,直到到達某個公共屏障點。利用柵欄,可以使線程相互等待,直到所有線程都到達某一點,然后柵欄將打開,所有線程將通過柵欄繼續執行。CyclicBarrier支持一個可選的 Runnable 參數,當線程通過柵欄時,runnable對象將被調用。構造函數CyclicBarrier(int parties, Runnable barrierAction),當線程在CyclicBarrier對象上調用await()方法時,柵欄的計數器將增加1,當計數器為parties時,柵欄將打開。

  區別:閉鎖用於所有線程等待一個外部事件的發生;柵欄則是所有線程相互等待,直到所有線程都到達某一點時才打開柵欄,然后線程可以繼續執行。

閉鎖示例:

  有五個人,一個裁判。這五個人同時跑,裁判開始計時,五個人都到終點了,裁判喊停,然后統計這五個人從開始跑到最后一個撞線用了多長時間。

import java.util.concurrent.CountDownLatch;

public class Race {

    public static void main(String[] args) {
        final int num = 5;
        final CountDownLatch begin = new CountDownLatch(1); final CountDownLatch end = new CountDownLatch(num); for (int i = 0; i < num; i++) {
            new Thread(new AWorker(i, begin, end)).start();
        }

        // judge prepare...
        try {
            Thread.sleep((long) (Math.random() * 5000));
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("judge say : run !");
        begin.countDown(); long startTime = System.currentTimeMillis();

        try {
            end.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long endTime = System.currentTimeMillis();
            System.out.println("judge say : all arrived !");
            System.out.println("spend time: " + (endTime - startTime));
        }

    }
}
class AWorker implements Runnable {
    final CountDownLatch begin;
    final CountDownLatch end;
    final int id;

    public AWorker(final int id, final CountDownLatch begin,
                   final CountDownLatch end) {
        this.id = id;
        this.begin = begin;
        this.end = end;
    }

    @Override
    public void run() {
        try {
            System.out.println(this.id + " ready !");
            begin.await(); // run...
            Thread.sleep((long) (Math.random() * 10000));
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            System.out.println(this.id + " arrived !");
            end.countDown();
        }
    }

}

柵欄示例:

  還是這五個人(這五個人真無聊..),這次沒裁判。規定五個人只要都跑到終點了,大家可以喝啤酒。但是,只要有一個人沒到終點,就不能喝。 這里也沒有要求大家要同時起跑(當然也可以,加latch)。

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Beer {

    public static void main(String[] args) {
        final int count = 5;
        final CyclicBarrier barrier = new CyclicBarrier(count, new Runnable() { @Override public void run() { System.out.println("drink beer!"); } }); // they do not have to start at the same time...
        for (int i = 0; i < count; i++) {
            new Thread(new Worker(i, barrier)).start();
        }
    }

}

class Worker implements Runnable {
    final int id;
    final CyclicBarrier barrier;

    public Worker(final int id, final CyclicBarrier barrier) {
        this.id = id;
        this.barrier = barrier;
    }

    @Override
    public void run() {
        try {
            System.out.println(this.id + "starts to run !");
            Thread.sleep((long) (Math.random() * 10000));
            System.out.println(this.id + "arrived !");
            this.barrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM