1. 程式人生 > >Java例項學習 Java併發程式設計之java.util.concurrent.CountDownLatch

Java例項學習 Java併發程式設計之java.util.concurrent.CountDownLatch

import java.util.concurrent.CountDownLatch;
/**
 * 工人類
 */
class Worker {
    private String name;        // 名字
    private long workDuration;  // 工作持續時間


    /**
     * 構造器
     */
    public Worker(String name, long workDuration) {
        this.name = name;
        this.workDuration = workDuration;
    }


    /**
     * 完成工作
     */
    public void doWork() {
        System.out.println(name + " begins to work...");
        try {
            Thread.sleep(workDuration); // 用休眠模擬工作執行的時間
        } catch(InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println(name + " has finished the job...");
    }
}

/**
 * 測試執行緒
 */
class WorkerTestThread implements Runnable {
    private Worker worker;
    private CountDownLatch cdLatch;

    public WorkerTestThread(Worker worker, CountDownLatch cdLatch) {
        this.worker = worker;
        this.cdLatch = cdLatch;
    }

    @Override
    public void run() {
        worker.doWork();        // 讓工人開始工作
        cdLatch.countDown();    // 工作完成後倒計時次數減1
    }
}

public class CountDownLatchTest {

    private static final int MAX_WORK_DURATION = 5000;  // 最大工作時間
    private static final int MIN_WORK_DURATION = 1000;  // 最小工作時間

    // 產生隨機的工作時間
    private static long getRandomWorkDuration(long min, long max) {
        return (long) (Math.random() * (max - min) + min);
    }

    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(2);   // 建立倒計時閂並指定倒計時次數為2
        Worker w1 = new Worker("駱昊", getRandomWorkDuration(MIN_WORK_DURATION, MAX_WORK_DURATION));
        Worker w2 = new Worker("王大錘", getRandomWorkDuration(MIN_WORK_DURATION, MAX_WORK_DURATION));

        new Thread(new WorkerTestThread(w1, latch)).start();
        new Thread(new WorkerTestThread(w2, latch)).start();

        try {
            latch.await();  // 等待倒計時閂減到0
            System.out.println("All jobs have been finished!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}