java 多線程(十三)

package com.thread.threadTest;

import sun.awt.windows.ThemeReader;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 同步工具類
 * CountDownLatch:猶如倒計時計數器,調用ContDownLatch對象的countDown方法就將計數器減一,
 * 當計數器到達0時,則所有等待者或者單個等待者開始執行。
 *
 * 例子:運動員百米賽跑.裁判哨響,線程執行,執行完畢,得到結果
 *
 */
public class CountDownLatchTest {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final CountDownLatch cdOrder = new CountDownLatch(1);
        final CountDownLatch cdAnswer = new CountDownLatch(3);
        for (int i=1;i<=3;i++){
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("線程"+Thread.currentThread().getName()+"正準備接受命令");
                        cdOrder.await();
                        System.out.println("線程"+Thread.currentThread().getName()+"已接受命令");
                        Thread.sleep((long) (Math.random()*10000));
                        System.out.println("線程"+Thread.currentThread().getName()+"迴應命令處理結果");
                        cdAnswer.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            };
            executorService.execute(runnable);
        }
        try{
            Thread.sleep((long) (Math.random()*10000));
            System.out.println("線程"+Thread.currentThread().getName()+"即將發佈命令");
            cdOrder.countDown();
            System.out.println("線程"+Thread.currentThread().getName()+"已發送命令,正在等待結果");
            cdAnswer.await();
            System.out.println("線程"+Thread.currentThread().getName()+"已收到所有響應結果");
        }catch (Exception e){
            e.printStackTrace();
        }
        executorService.shutdown();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章