CountDownLatch和CyclicBarrier簡單使用

CountDownLatch:一般是阻塞主線程,等待其他子線程全部完成後,再繼續執行主線程。調用 latch.await() 方法的線程處於阻塞狀態,latch.countDown() 達到一定的次數就會喚醒被阻塞的線程。
CyclicBarrier:調用 barrier.await() 方法的線程處於阻塞狀態、相互等待,barrier.await() 方法被調用達到一定的數量後,被阻塞的線程一起執行任務。

下面是CountDownLatch和CyclicBarrier組合使用,模擬併發:

public class CountDownLatchAndCyclicBarrier extends Thread {
    private CyclicBarrier barrier;
    private CountDownLatch latch;
    private static int num;

    CountDownLatchAndCyclicBarrier(CyclicBarrier barrier, CountDownLatch latch) {
        this.barrier = barrier;
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            barrier.await(); // 創建好的線程都會在此阻塞、直到 barrier.await() 被調用20次
            for (int i = 0; i < 10000; i++) {
                add();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown(); // 所有線程都執行完此方法,主線程才能被喚醒
        }
    }

    // 有【static】是類鎖、所有線程共享一把鎖;沒有【static】是對象鎖、一個對象一把鎖、不安全,感興趣的人可以去掉試試看。
    private static synchronized void add() {
        num++;
    }

    public static void main(String[] args) throws Exception {
        int count = 20;
        CyclicBarrier barrier = new CyclicBarrier(count);
        CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new CountDownLatchAndCyclicBarrier(barrier, latch).start();;
        }
        latch.await(); // 阻塞主線程,等待20個線程全部結束
        System.out.println(CountDownLatchAndCyclicBarrier.num);
    }
}

下面是CyclicBarrier模擬運動員準備、起跑、結束的過程:

public class CyclicBarrierTest {
	public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
		ExecutorService executor = Executors.newFixedThreadPool(3);
		CyclicBarrier start = new CyclicBarrier(3); // 三個選手,三個起跑柵欄
		CyclicBarrier end = new CyclicBarrier(4);	// 三個選手柵欄 + 一個結束標誌柵欄

		while (true) {
			executor.execute(new Player(start, end, "張三"));
			executor.execute(new Player(start, end, "李四"));
			executor.execute(new Player(start, end, "王五"));

			end.await();
			System.out.println("比賽結束==================================");
		}
	}
}
public class Player extends Thread {

	private CyclicBarrier start;
	private CyclicBarrier end;
	private String name;

	public Player(CyclicBarrier start, CyclicBarrier end, String name) {
		this.start = start;
		this.end = end;
		this.name = name;
	}

	@Override
	public void run() {
		try {
			int a = new Random().nextInt(5) + 1;
			System.out.println(this.name + " 準備耗時: " + a + "s");
			Thread.sleep(a * 1000);

			System.out.println(this.name + " 準備好了。。。 等待其他人。。。");
			this.start.await();

			System.out.println(this.name + " 開始起跑。。。go go go");
			int b = new Random().nextInt(5) + 2;
			Thread.sleep(b * 1000);

			System.out.println(this.name + " 到達終點!!!  耗時: " + b + "s");
			this.end.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章