1. 程式人生 > >CountDownLatch和CyclicBarrier

CountDownLatch和CyclicBarrier

fin set方法 ren div exce name JD 繼續 override

CountDownLatch

CountDownLatch是jdk5 java.util.concurrent新增的的工具類

使用場景。導出excel需要解析創建多個sheel。創建多線程並行執行。執行完畢 相應給客戶端

public static void main(String[] args) throws InterruptedException {
        final java.util.concurrent.CountDownLatch countDownLatch=new CountDownLatch(2);
        new Thread(new Runnable() {
            
            @Override
            
public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // TODO Auto-generated method stub System.out.println(Thread.currentThread().getName()+"解析數據並寫入sheel"); countDownLatch.countDown(); } }).start();
new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }
// TODO Auto-generated method stub System.out.println(Thread.currentThread().getName()+"解析數據並寫入sheel"); countDownLatch.countDown(); } }).start(); countDownLatch.await(); System.out.println("響應給客戶端"); }

打印

Thread-0解析數據並寫入sheel
Thread-1解析數據並寫入sheel
響應給客戶端

  

await的線程會阻塞等待其他線程調用countDown 每調用一次number-1 直到為0 countDown 可以是多個線程 也可以是一個線程的多個步驟執行完畢

CyclicBarrier

CyclicBarrier跟CountDownLatch的區別

1.CountDownLatch是一個線程阻塞等待多個線程喚醒。 CyclicBarrier是阻塞多個線程直到多個線程調用await才繼續往下執行

2.CountDownLatch計數器只能使用一次,CyclicBarrier可以使用多次 通過調用reset方法

public class CyclicBarrierTest implements Runnable {
	CyclicBarrier barrier;

	public CyclicBarrierTest(CyclicBarrier barrier) {
		this.barrier = barrier;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
	 System.out.println("讀取配置");
	 try {
		barrier.await();
	} catch (InterruptedException | BrokenBarrierException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 System.out.println("進行初始化");
	}

	public static void main(String[] args) {
		CyclicBarrier barrier=new CyclicBarrier(3);
		new Thread(new CyclicBarrierTest(barrier)).start();
		new Thread(new CyclicBarrierTest(barrier)).start();
		new Thread(new CyclicBarrierTest(barrier)).start();

	}

}

  3個線程在執行讀取完畢配置會等待其他線程都執行讀取完畢後才往下執行

CountDownLatch和CyclicBarrier