【轉】Java裏如何實現線程間通訊

正常狀況下,每一個子線程完成各自的任務就能夠結束了。不過有的時候,咱們但願多個線程協同工做來完成某個任務,這時就涉及到了線程間通訊了。java

本文涉及到的知識點:thread.join(), object.wait(), object.notify(), CountdownLatch, CyclicBarrier, FutureTask, Callable 等。git

本文涉及代碼:github

https://github.com/wingjay/HelloJava/blob/master/multi-thread/src/ForArticle.java數據結構

下面我從幾個例子做爲切入點來說解下 Java 裏有哪些方法來實現線程間通訊。dom

  • 如何讓兩個線程依次執行?
  • 那如何讓兩個線程按照指定方式有序交叉運行呢?
  • 四個線程 A B C D,其中 D 要等到 A B C 全執行完畢後才執行,並且 A B C 是同步運行的
  • 三個運動員各自準備,等到三我的都準備好後,再一塊兒跑
  • 子線程完成某件任務後,把獲得的結果回傳給主線程

如何讓兩個線程依次執行?

假設有兩個線程,一個是線程 A,另外一個是線程 B,兩個線程分別依次打印 1-3 三個數字便可。咱們來看下代碼:ide

 1 private static void demo1() {
 2     Thread A = new Thread(new Runnable() {
 3         @Override
 4         public void run() {
 5             printNumber("A");
 6         }
 7     });
 8     Thread B = new Thread(new Runnable() {
 9         @Override
10         public void run() {
11             printNumber("B");
12         }
13     });
14     A.start();
15     B.start();
16 }

其中的 printNumber(String) 實現以下,用來依次打印 1, 2, 3 三個數字:spa

 1 private static void printNumber(String threadName) {
 2     int i=0;
 3     while (i++ < 3) {
 4         try {
 5             Thread.sleep(100);
 6         } catch (InterruptedException e) {
 7             e.printStackTrace();
 8         }
 9         System.out.println(threadName + "print:" + i);
10     }
11 }

這時咱們獲得的結果是:線程

1 B print: 1
2 A print: 1
3 B print: 2
4 A print: 2
5 B print: 3
6 A print: 3

能夠看到 A 和 B 是同時打印的。code

那麼,若是咱們但願 B 在 A 所有打印 完後再開始打印呢?咱們能夠利用 thread.join() 方法,代碼以下:對象

 1 private static void demo2() {
 2     Thread A = new Thread(new Runnable() {
 3         @Override
 4         public void run() {
 5             printNumber("A");
 6         }
 7     });
 8     Thread B = new Thread(new Runnable() {
 9         @Override
10         public void run() {
11             System.out.println("B 開始等待 A");
12             try {
13                 A.join();
14             } catch (InterruptedException e) {
15                 e.printStackTrace();
16             }
17             printNumber("B");
18         }
19     });
20     B.start();
21     A.start();
22 }

獲得的結果以下:

1 B 開始等待 A
2 A print: 1
3 A print: 2
4 A print: 3
5  
6 B print: 1
7 B print: 2
8 B print: 3

因此咱們能看到 A.join() 方法會讓 B一直等待直到 A 運行完畢。

那如何讓 兩個線程按照指定方式有序交叉運行呢?

仍是上面那個例子,我如今但願 A 在打印完 1 後,再讓 B 打印 1, 2, 3,最後再回到 A 繼續打印 2, 3。這種需求下,顯然 Thread.join() 已經不能知足了。咱們須要更細粒度的鎖來控制執行順序。

這裏,咱們能夠利用 object.wait() 和 object.notify() 兩個方法來實現。代碼以下:

 1 /**
 2  * A 1, B 1, B 2, B 3, A 2, A 3
 3  */
 4 private static void demo3() {
 5     Object lock = new Object();
 6     Thread A = new Thread(new Runnable() {
 7         @Override
 8         public void run() {
 9             synchronized (lock) {
10                 System.out.println("A 1");
11                 try {
12                     lock.wait();
13                 } catch (InterruptedException e) {
14                     e.printStackTrace();
15                 }
16                 System.out.println("A 2");
17                 System.out.println("A 3");
18             }
19         }
20     });
21     Thread B = new Thread(new Runnable() {
22         @Override
23         public void run() {
24             synchronized (lock) {
25                 System.out.println("B 1");
26                 System.out.println("B 2");
27                 System.out.println("B 3");
28                 lock.notify();
29             }
30         }
31     });
32     A.start();
33     B.start();
34 }

打印結果以下:

1 A 1
2 A waiting…
3  
4 B 1
5 B 2
6 B 3
7 A 2
8 A 3

正是咱們要的結果。

那麼,這個過程發生了什麼呢?

  1. 首先建立一個 A 和 B 共享的對象鎖 lock = new Object();
  2. 當 A 獲得鎖後,先打印 1,而後調用 lock.wait() 方法,交出鎖的控制權,進入 wait 狀態;
  3. 對 B 而言,因爲 A 最開始獲得了鎖,致使 B 沒法執行;直到 A 調用 lock.wait() 釋放控制權後, B 才獲得了鎖;
  4. B 在獲得鎖後打印 1, 2, 3;而後調用 lock.notify() 方法,喚醒正在 wait 的 A;
  5. A 被喚醒後,繼續打印剩下的 2,3。

爲了更好理解,我在上面的代碼里加上 log 方便讀者查看。

 1 private static void demo3() {
 2     Object lock = new Object();
 3     Thread A = new Thread(new Runnable() {
 4         @Override
 5         public void run() {
 6             System.out.println("INFO: A 等待鎖");
 7             synchronized (lock) {
 8                 System.out.println("INFO: A 獲得了鎖 lock");
 9                 System.out.println("A 1");
10                 try {
11                     System.out.println("INFO: A 準備進入等待狀態,放棄鎖 lock 的控制權");
12                     lock.wait();
13                 } catch (InterruptedException e) {
14                     e.printStackTrace();
15                 }
16                 System.out.println("INFO: 有人喚醒了 A, A 從新得到鎖 lock");
17                 System.out.println("A 2");
18                 System.out.println("A 3");
19             }
20         }
21     });
22     Thread B = new Thread(new Runnable() {
23         @Override
24         public void run() {
25             System.out.println("INFO: B 等待鎖");
26             synchronized (lock) {
27                 System.out.println("INFO: B 獲得了鎖 lock");
28                 System.out.println("B 1");
29                 System.out.println("B 2");
30                 System.out.println("B 3");
31                 System.out.println("INFO: B 打印完畢,調用 notify 方法");
32                 lock.notify();
33             }
34         }
35     });
36     A.start();
37     B.start();
38 }

打印結果以下:

 1 INFO: A 等待鎖
 2 INFO: A 獲得了鎖 lock
 3 A 1
 4 INFO: A 準備進入等待狀態,調用 lock.wait() 放棄鎖 lock 的控制權
 5 INFO: B 等待鎖
 6 INFO: B 獲得了鎖 lock
 7 B 1
 8 B 2
 9 B 3
10 INFO: B 打印完畢,調用 lock.notify() 方法
11 INFO: 有人喚醒了 A, A 從新得到鎖 lock
12 A 2
13 A 3

四個線程 A B C D,其中 D 要等到 A B C 全執行完畢後才執行,並且 A B C 是同步運行的

最開始咱們介紹了 thread.join(),可讓一個線程等另外一個線程運行完畢後再繼續執行,那咱們能夠在 D 線程裏依次 join A B C,不過這也就使得 A B C 必須依次執行,而咱們要的是這三者能同步運行。

或者說,咱們但願達到的目的是:A B C 三個線程同時運行,各自獨立運行完後通知 D;對 D 而言,只要 A B C 都運行完了,D 再開始運行。針對這種狀況,咱們能夠利用 CountdownLatch 來實現這類通訊方式。它的基本用法是:

  1. 建立一個計數器,設置初始值,CountdownLatch countDownLatch = new CountDownLatch(2);
  2. 在 等待線程 裏調用 countDownLatch.await() 方法,進入等待狀態,直到計數值變成 0;
  3. 在 其餘線程 裏,調用 countDownLatch.countDown() 方法,該方法會將計數值減少 1;
  4. 當 其餘線程 的 countDown() 方法把計數值變成 0 時,等待線程 裏的 countDownLatch.await() 當即退出,繼續執行下面的代碼。

實現代碼以下:

 1 private static void runDAfterABC() {
 2     int worker = 3;
 3     CountDownLatch countDownLatch = new CountDownLatch(worker);
 4     new Thread(new Runnable() {
 5         @Override
 6         public void run() {
 7             System.out.println("D is waiting for other three threads");
 8             try {
 9                 countDownLatch.await();
10                 System.out.println("All done, D starts working");
11             } catch (InterruptedException e) {
12                 e.printStackTrace();
13             }
14         }
15     }).start();
16     for (char threadName='A'; threadName <= 'C'; threadName++) {
17         final String tN = String.valueOf(threadName);
18         new Thread(new Runnable() {
19             @Override
20             public void run() {
21                 System.out.println(tN + "is working");
22                 try {
23                     Thread.sleep(100);
24                 } catch (Exception e) {
25                     e.printStackTrace();
26                 }
27                 System.out.println(tN + "finished");
28                 countDownLatch.countDown();
29             }
30         }).start();
31     }
32 }

下面是運行結果:

1 D is waiting for other three threads
2 A is working
3 B is working
4 C is working
5  
6 A finished
7 C finished
8 B finished
9 All done, D starts working

其實簡單點來講,CountDownLatch 就是一個倒計數器,咱們把初始計數值設置爲3,當 D 運行時,先調用 countDownLatch.await() 檢查計數器值是否爲 0,若不爲 0 則保持等待狀態;當A B C 各自運行完後都會利用countDownLatch.countDown(),將倒計數器減 1,當三個都運行完後,計數器被減至 0;此時當即觸發 D 的 await() 運行結束,繼續向下執行。

所以,CountDownLatch 適用於一個線程去等待多個線程的狀況。

三個運動員各自準備,等到三我的都準備好後,再一塊兒跑

上面是一個形象的比喻,針對 線程 A B C 各自開始準備,直到三者都準備完畢,而後再同時運行 。也就是要實現一種 線程之間互相等待 的效果,那應該怎麼來實現呢?

上面的 CountDownLatch 能夠用來倒計數,但當計數完畢,只有一個線程的 await() 會獲得響應,沒法讓多個線程同時觸發。

爲了實現線程間互相等待這種需求,咱們能夠利用 CyclicBarrier 數據結構,它的基本用法是:

  1. 先建立一個公共 CyclicBarrier 對象,設置 同時等待 的線程數,CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
  2. 這些線程同時開始本身作準備,自身準備完畢後,須要等待別人準備完畢,這時調用 cyclicBarrier.await(); 便可開始等待別人;
  3. 當指定的 同時等待 的線程數都調用了 cyclicBarrier.await();時,意味着這些線程都準備完畢好,而後這些線程才 同時繼續執行。

實現代碼以下,設想有三個跑步運動員,各自準備好後等待其餘人,所有準備好後纔開始跑:

 1 private static void runABCWhenAllReady() {
 2     int runner = 3;
 3     CyclicBarrier cyclicBarrier = new CyclicBarrier(runner);
 4     final Random random = new Random();
 5     for (char runnerName='A'; runnerName <= 'C'; runnerName++) {
 6         final String rN = String.valueOf(runnerName);
 7         new Thread(new Runnable() {
 8             @Override
 9             public void run() {
10                 long prepareTime = random.nextInt(10000) + 100;
11                 System.out.println(rN + "is preparing for time:" + prepareTime);
12                 try {
13                     Thread.sleep(prepareTime);
14                 } catch (Exception e) {
15                     e.printStackTrace();
16                 }
17                 try {
18                     System.out.println(rN + "is prepared, waiting for others");
19                     cyclicBarrier.await(); // 當前運動員準備完畢,等待別人準備好
20                 } catch (InterruptedException e) {
21                     e.printStackTrace();
22                 } catch (BrokenBarrierException e) {
23                     e.printStackTrace();
24                 }
25                 System.out.println(rN + "starts running"); // 全部運動員都準備好了,一塊兒開始跑
26             }
27         }).start();
28     }
29 }

打印的結果以下:

 1 A is preparing for time: 4131
 2 B is preparing for time: 6349
 3 C is preparing for time: 8206
 4  
 5 A is prepared, waiting for others
 6  
 7 B is prepared, waiting for others
 8  
 9 C is prepared, waiting for others
10  
11 C starts running
12 A starts running
13 B starts running

子線程完成某件任務後,把獲得的結果回傳給主線程

實際的開發中,咱們常常要建立子線程來作一些耗時任務,而後把任務執行結果回傳給主線程使用,這種狀況在 Java 裏要如何實現呢?

回顧線程的建立,咱們通常會把 Runnable 對象傳給 Thread 去執行。Runnable定義以下:

1 public interface Runnable {
2     public abstract void run();
3 }

能夠看到 run() 在執行完後不會返回任何結果。那若是但願返回結果呢?這裏能夠利用另外一個相似的接口類 Callable:

 1 @FunctionalInterface
 2 public interface Callable<V> {
 3     /**
 4      * Computes a result, or throws an exception if unable to do so.
 5      *
 6      * @return computed result
 7      * @throws Exception if unable to compute a result
 8      */
 9     V call() throws Exception;
10 }

能夠看出 Callable 最大區別就是返回範型 V 結果。

那麼下一個問題就是,如何把子線程的結果回傳回來呢?在 Java 裏,有一個類是配合 Callable 使用的:FutureTask,不過注意,它獲取結果的 get 方法會阻塞主線程。

舉例,咱們想讓子線程去計算從 1 加到 100,並把算出的結果返回到主線程。

 1 private static void doTaskWithResultInWorker() {
 2     Callable<Integer> callable = new Callable<Integer>() {
 3         @Override
 4         public Integer call() throws Exception {
 5             System.out.println("Task starts");
 6             Thread.sleep(1000);
 7             int result = 0;
 8             for (int i=0; i<=100; i++) {
 9                 result += i;
10             }
11             System.out.println("Task finished and return result");
12             return result;
13         }
14     };
15     FutureTask<Integer> futureTask = new FutureTask<>(callable);
16     new Thread(futureTask).start();
17     try {
18         System.out.println("Before futureTask.get()");
19         System.out.println("Result:" + futureTask.get());
20         System.out.println("After futureTask.get()");
21     } catch (InterruptedException e) {
22         e.printStackTrace();
23     } catch (ExecutionException e) {
24         e.printStackTrace();
25     }
26 }

打印結果以下:

1 Before futureTask.get()
2  
3 Task starts
4 Task finished and return result
5  
6 Result: 5050
7 After futureTask.get()

能夠看到,主線程調用 futureTask.get() 方法時阻塞主線程;而後 Callable 內部開始執行,並返回運算結果;此時 futureTask.get() 獲得結果,主線程恢復運行。

這裏咱們能夠學到,經過 FutureTask 和 Callable 能夠直接在主線程得到子線程的運算結果,只不過須要阻塞主線程。固然,若是不但願阻塞主線程,能夠考慮利用 ExecutorService,把 FutureTask 放到線程池去管理執行。

相關文章
相關標籤/搜索