有時線程之間須要同步。現有以下要求java
多線程執行job的兩個方法:全部doJob1()執行完以後,doJob2()纔開始執行。多線程
package com.wss.lsl.test.driven.runnable; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * 多線程執行job的兩個方法:全部doJob1()執行完以後,doJob2()纔開始執行. * <p> * 使用關卡實現,doJob1()執行完以後,在關卡等待,直到最後一個線程執行完纔打開關卡 * </p> * * @author Administrator * */ public class Job { public void doJob1() { System.out.println("doJob1"); } public void doJob2() { System.out.println("doJob2"); } public void run(int threadCount) { CyclicBarrier entryBarrier = new CyclicBarrier(threadCount); CyclicBarrier exitBarrier = new CyclicBarrier(threadCount + 1); for (int i = 0; i < threadCount; i++) { new Thread(new RunJob(this, entryBarrier, exitBarrier)).start(); } try { exitBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } static class RunJob implements Runnable { private Job job; // 進入的關卡 private CyclicBarrier entryBarrier; // 退出的關卡 private CyclicBarrier exitBarrier; public RunJob(Job job, CyclicBarrier entryBarrier, CyclicBarrier exitBarrier) { super(); this.job = job; this.entryBarrier = entryBarrier; this.exitBarrier = exitBarrier; } @Override public void run() { try { job.doJob1(); // 在關卡等待,直到全部的doJob1執行完 entryBarrier.await(); job.doJob2(); // 配合主線程退出,避免主線程退出而致使程序關閉 exitBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } } }