代碼詳解の使用CountDownLatch解決面試問題:T1和T2線程執行計算,T3線程計算結果的統計

package com.sdmjhca.springBootDemo.synchronizedtest;

import java.util.concurrent.CountDownLatch;

/**
 * 例子:T1T2線程執行計算,T3線程進行T1T2結果的統計
 * 思路定義一個鎖計數器2的線程併發類,T3通過await方法進行鎖等待,T1執行完成後計數器-1T2完成後計數器-1 * 當計數器爲0後,T3開始執行統計方法,得到最終計算結果
 * @author JHMI on 2017/8/18.
 */
public class SynchronizedMain {
    private static CountDownLatch start = new CountDownLatch(1);
    private static CountDownLatch end = new CountDownLatch(2);
    private static int i = 1;

    private static int j = 1;
    public static void main(String args[]) throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    start.await();
                    System.out.println("T1開始執行");

                    //SynchronizedTest.staticIn.method1();
                    i++;
                    //Thread.sleep(1000);
                    end.countDown();
                    System.out.println("T1計算結束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    start.await();
                    System.out.println("T2開始執行");

                   // SynchronizedTest.staticIn.method2();

                    j++;
                    //Thread.sleep(1000);
                    end.countDown();
                    System.out.println("T2執行結束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    start.await();
                    System.out.println("T3開始執行,進入等待狀態");
                    end.await();
                    System.out.println("獲得鎖 開始執行T3");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //Thread.sleep(1000);

                int c = i+j;
                System.out.println("統計結果="+c);
                System.out.println("T3執行結束");

            }
        });
        t1.start();
        t2.start();
        t3.start();
        start.countDown();
       /* i = i+j;
        System.out.println("i="+i);*/
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章