正常情況下,每個子線程完成各自的任務就可以結束了。不過有的時候,我們希望多個線程協同工作來完成某個任務,這時就涉及到了線程間通信了。
本文涉及到的知識點:thread.join(), object.wait(), object.notify(), CountdownLatch, CyclicBarrier, FutureTask, Callable 等。
本文涉及代碼:
https://github.com/wingjay/HelloJava/blob/master/multi-thread/src/ForArticle.java
下面我從幾個例子作為切入點來講解下 Java 里有哪些方法來實現線程間通信。
如何讓兩個線程依次執行?
那如何讓 兩個線程按照指定方式有序交叉運行呢?
四個線程 A B C D,其中 D 要等到 A B C 全執行完畢后才執行,而且 A B C 是同步運行的
三個運動員各自準備,等到三個人都準備好后,再一起跑
子線程完成某件任務后,把得到的結果回傳給主線程
如何讓兩個線程依次執行?
假設有兩個線程,一個是線程 A,另一個是線程 B,兩個線程分別依次打印 1-3 三個數字即可。我們來看下代碼:
1private 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 三個數字:
1private 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}
這時我們得到的結果是:
B print: 1
A print: 1
B print: 2
A print: 2
B print: 3
A print: 3
可以看到 A 和 B 是同時打印的。
那么,如果我們希望 B 在 A 全部打印 完后再開始打印呢?我們可以利用 thread.join() 方法,代碼如下:
1private 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}
得到的結果如下:
B 開始等待 A
A print: 1
A print: 2
A print: 3
B print: 1
B print: 2
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 */
4private 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}
打印結果如下:
A 1
A waiting…
B 1
B 2
B 3
A 2
A 3
正是我們要的結果。
那么,這個過程發生了什么呢?
首先創建一個 A 和 B 共享的對象鎖 lock = new Object();
當 A 得到鎖后,先打印 1,然后調用 lock.wait() 方法,交出鎖的控制權,進入 wait 狀態;
對 B 而言,由于 A 最開始得到了鎖,導致 B 無法執行;直到 A 調用 lock.wait() 釋放控制權后, B 才得到了鎖;
B 在得到鎖后打印 1, 2, 3;然后調用 lock.notify() 方法,喚醒正在 wait 的 A;
A 被喚醒后,繼續打印剩下的 2,3。
為了更好理解,我在上面的代碼里加上 log 方便讀者查看。
1private 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}
打印結果如下:
INFO: A 等待鎖
INFO: A 得到了鎖 lock
A 1
INFO: A 準備進入等待狀態,調用 lock.wait() 放棄鎖 lock 的控制權
INFO: B 等待鎖
INFO: B 得到了鎖 lock
B 1
B 2
B 3
INFO: B 打印完畢,調用 lock.notify() 方法
INFO: 有人喚醒了 A, A 重新獲得鎖 lock
A 2
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 來實現這類通信方式。它的基本用法是:
創建一個計數器,設置初始值,CountdownLatch countDownLatch = new CountDownLatch(2);
在 等待線程 里調用 countDownLatch.await() 方法,進入等待狀態,直到計數值變成 0;
在 其他線程 里,調用 countDownLatch.countDown() 方法,該方法會將計數值減小 1;
當 其他線程 的 countDown() 方法把計數值變成 0 時,等待線程 里的 countDownLatch.await() 立即退出,繼續執行下面的代碼。
實現代碼如下:
1private 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}
下面是運行結果:
D is waiting for other three threads
A is working
B is working
C is working
A finished
C finished
B finished
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 數據結構,它的基本用法是:
先創建一個公共 CyclicBarrier 對象,設置 同時等待 的線程數,CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
這些線程同時開始自己做準備,自身準備完畢后,需要等待別人準備完畢,這時調用 cyclicBarrier.await(); 即可開始等待別人;
當指定的 同時等待 的線程數都調用了 cyclicBarrier.await();時,意味著這些線程都準備完畢好,然后這些線程才 同時繼續執行。
實現代碼如下,設想有三個跑步運動員,各自準備好后等待其他人,全部準備好后才開始跑:
1private 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
12 System.out.println(rN + “is preparing for time:” + prepareTime);
13 try {
14 Thread.sleep(prepareTime);
15 } catch (Exception e) {
16 e.printStackTrace();
17 }
18 try {
19 System.out.println(rN + “is prepared, waiting for others”);
20 cyclicBarrier.await(); // 當前運動員準備完畢,等待別人準備好
21 } catch (InterruptedException e) {
22 e.printStackTrace();
23 } catch (BrokenBarrierException e) {
24 e.printStackTrace();
25 }
26 System.out.println(rN + “starts running”); // 所有運動員都準備好了,一起開始跑
27 }
28 }).start();
29 }
30}
31 }
打印的結果如下:
A is preparing for time: 4131
B is preparing for time: 6349
C is preparing for time: 8206
A is prepared, waiting for others
B is prepared, waiting for others
C is prepared, waiting for others
C starts running
A starts running
B starts running
子線程完成某件任務后,把得到的結果回傳給主線程
實際的開發中,我們經常要創建子線程來做一些耗時任務,然后把任務執行結果回傳給主線程使用,這種情況在 Java 里要如何實現呢?
回顧線程的創建,我們一般會把 Runnable 對象傳給 Thread 去執行。Runnable定義如下:
1public interface Runnable {
public abstract void run();
}
可以看到 run() 在執行完后不會返回任何結果。那如果希望返回結果呢?這里可以利用另一個類似的接口類 Callable:
1@FunctionalInterface
2public interface Callable {
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,并把算出的結果返回到主線程。
1private static void doTaskWithResultInWorker() {
2 Callable callable = new Callable() {
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 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}
打印結果如下:
Before futureTask.get()
Task starts
Task finished and return result
Result: 5050
After futureTask.get()
可以看到,主線程調用 futureTask.get() 方法時阻塞主線程;然后 Callable 內部開始執行,并返回運算結果;此時 futureTask.get() 得到結果,主線程恢復運行。
這里我們可以學到,通過 FutureTask 和 Callable 可以直接在主線程獲得子線程的運算結果,只不過需要阻塞主線程。當然,如果不希望阻塞主線程,可以考慮利用 ExecutorService,把 FutureTask 放到線程池去管理執行。
小結:多線程是現代語言的共同特性,而線程間通信、線程同步、線程安全是很重要的話題。本文針對 Java 的線程間通信進行了大致的講解,后續還會對線程同步、線程安全進行講解。 大家可以點擊加入群:478052716【JAVA高級程序員】里面有Java高級大牛直播講解知識點 走的就是高端路線(如果你想跳槽換工作 但是技術又不夠 或者工作上遇到了瓶頸 我這里有一個JAVA的免費直播課程 講的是高端的知識點基礎不好的勿入喲 只要你有1-5年的開發經驗可以加群找我要課堂鏈接 注意:是免費的 沒有開發經驗勿入哦)