前言
開發中不免會遇到需要所有子線程執行完畢通知主線程處理某些邏輯的場景。
或者是線程 A 在執行到某個條件通知線程 B 執行某個操作。
可以通過以下幾種方式實現:
(1)等待通知機制
兩個線程通過對同一對象調用等待 wait() 和通知 notify() 方法來進行通訊。
如兩個線程交替打印奇偶數:
public class TwoThreadWaitNotify {
private int start = 1;
private boolean flag = false;
public static void main(String[] args) {
TwoThreadWaitNotify twoThread = new TwoThreadWaitNotify();
Thread t1 = new Thread(new OuNum(twoThread));
t1.setName("A");
Thread t2 = new Thread(new JiNum(twoThread));
t2.setName("B");
t1.start();
t2.start();
}
/**
* 偶數線程
*/
public static class OuNum implements Runnable {
private TwoThreadWaitNotify number;
public OuNum(TwoThreadWaitNotify number) {
this.number = number;
}
@Override
public void run() {
while (number.start <= 100) {
synchronized (TwoThreadWaitNotify.class) {
System.out.println("偶數線程搶到鎖了");
if (number.flag) {
System.out.println(Thread.currentThread().getName() + "+-+偶數" + number.start);
number.start++;
number.flag = false;
TwoThreadWaitNotify.class.notify();
}else {
try {
TwoThreadWaitNotify.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* 奇數線程
*/
public static class JiNum implements Runnable {
private TwoThreadWaitNotify number;
public JiNum(TwoThreadWaitNotify number) {
this.number = number;
}
@Override
public void run() {
while (number.start <= 100) {
synchronized (TwoThreadWaitNotify.class) {
System.out.println("奇數線程搶到鎖了");
if (!number.flag) {
System.out.println(Thread.currentThread().getName() + "+-+奇數" + number.start);
number.start++;
number.flag = true;
TwoThreadWaitNotify.class.notify();
}else {
try {
TwoThreadWaitNotify.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
這裏的線程 A 和線程 B 都對同一個對象 TwoThreadWaitNotify.class
獲取鎖,A 線程調用了同步對象的 wait() 方法釋放了鎖並進入 WAITING
狀態。
B 線程調用了 notify() 方法,這樣 A 線程收到通知之後就可以從 wait() 方法中返回。
這裏利用了 TwoThreadWaitNotify.class
對象完成了通信。
有一些需要注意:
- wait() 、notify()、notifyAll() 調用的前提都是獲得了對象的鎖(也可稱爲對象監視器)。
- 調用 wait() 方法後線程會釋放鎖,進入
WAITING
狀態,該線程也會被移動到等待隊列中。 - 調用 notify() 方法會將等待隊列中的線程移動到同步隊列中,線程狀態也會更新爲
BLOCKED
- 從 wait() 方法返回的前提是調用 notify() 方法的線程釋放鎖,wait() 方法的線程獲得鎖。
等待通知有着一個經典範式:
線程 A 作爲消費者:
- 獲取對象的鎖。
- 進入 while(判斷條件),並調用 wait() 方法。
- 當條件滿足跳出循環執行具體處理邏輯。
線程 B 作爲生產者:
- 獲取對象鎖。
- 更改與線程 A 共用的判斷條件。
- 調用 notify() 方法。
僞代碼如下:
//Thread A
synchronized(Object){
while(條件){
Object.wait();
}
//do something
}
//Thread B
synchronized(Object){
條件=false;//改變條件
Object.notify();
}
join() 方法
private static void join() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("running");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}) ;
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("running2");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}) ;
t1.start();
t2.start();
//等待線程1終止
t1.join();
//等待線程2終止
t2.join();
LOGGER.info("main over");
}
在 t1.join()
時會一直阻塞到 t1 執行完畢,所以最終主線程會等待 t1 和 t2 線程執行完畢。
在 join 線程完成後會調用 notifyAll() 方法,是在 JVM 實現中調用,所以這裏看不出來。
(2)volatile 共享內存
因爲 Java 是採用共享內存的方式進行線程通信的,所以可以採用以下方式用主線程關閉 A 線程:
public class Volatile implements Runnable{
private static volatile boolean flag = true ;
@Override
public void run() {
while (flag){
System.out.println(Thread.currentThread().getName() + "正在運行。。。");
}
System.out.println(Thread.currentThread().getName() +"執行完畢");
}
public static void main(String[] args) throws InterruptedException {
Volatile aVolatile = new Volatile();
new Thread(aVolatile,"thread A").start();
System.out.println("main 線程正在運行") ;
TimeUnit.MILLISECONDS.sleep(100) ;
aVolatile.stopThread();
}
private void stopThread(){
flag = false ;
}
}
這裏的 flag 存放於主內存中,所以主線程和線程 A 都可以看到。
flag 採用 volatile 修飾主要是爲了內存可見性。
(3)CountDownLatch 併發工具
CountDownLatch 可以實現 join 相同的功能,但是更加的靈活。
private static void countDownLatch() throws Exception{
int thread = 3 ;
long start = System.currentTimeMillis();
final CountDownLatch countDown = new CountDownLatch(thread);
for (int i= 0 ;i<thread ; i++){
new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("thread run");
try {
Thread.sleep(2000);
countDown.countDown();
LOGGER.info("thread end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
countDown.await();
long stop = System.currentTimeMillis();
LOGGER.info("main over total time={}",stop-start);
}
CountDownLatch 也是基於 AQS(AbstractQueuedSynchronizer) 實現的
- 初始化一個 CountDownLatch 時告訴併發的線程,然後在每個線程處理完畢之後調用 countDown() 方法。
- 該方法會將 AQS 內置的一個 state 狀態 -1 。
- 最終在主線程調用 await() 方法,它會阻塞直到
state == 0
的時候返回。
(4)CyclicBarrier 併發工具
private static void cyclicBarrier() throws Exception {
CyclicBarrier cyclicBarrier = new CyclicBarrier(3) ;
new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("thread run");
try {
cyclicBarrier.await() ;
} catch (Exception e) {
e.printStackTrace();
}
LOGGER.info("thread end do something");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("thread run");
try {
cyclicBarrier.await() ;
} catch (Exception e) {
e.printStackTrace();
}
LOGGER.info("thread end do something");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("thread run");
try {
Thread.sleep(5000);
cyclicBarrier.await() ;
} catch (Exception e) {
e.printStackTrace();
}
LOGGER.info("thread end do something");
}
}).start();
LOGGER.info("main thread");
}
CyclicBarrier 中文名叫做屏障或者是柵欄,也可以用於線程間通信。
它可以等待 N 個線程都達到某個狀態後繼續運行的效果。
- 首先初始化線程參與者。
- 調用
await()
將會在所有參與者線程都調用之前等待。 - 直到所有參與者都調用了
await()
後,所有線程從await()
返回繼續後續邏輯。
(5)線程響應中斷
public class StopThread implements Runnable {
@Override
public void run() {
while ( !Thread.currentThread().isInterrupted()) {
// 線程執行具體邏輯
System.out.println(Thread.currentThread().getName() + "運行中。。");
}
System.out.println(Thread.currentThread().getName() + "退出。。");
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new StopThread(), "thread A");
thread.start();
System.out.println("main 線程正在運行") ;
TimeUnit.MILLISECONDS.sleep(10) ;
thread.interrupt();
}
}
可以採用中斷線程的方式來通信,調用了 thread.interrupt()
方法其實就是將 thread 中的一個標誌屬性置爲了 true。
並不是說調用了該方法就可以中斷線程,如果不對這個標誌進行響應其實是沒有什麼作用(這裏對這個標誌進行了判斷)。
但是如果拋出了 InterruptedException 異常,該標誌就會被 JVM 重置爲 false。
(6)線程池 awaitTermination() 方法
如果是用線程池來管理線程,可以使用以下方式來讓主線程等待線程池中所有任務執行完畢:
private static void executorService() throws Exception{
BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(10) ;
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5,5,1, TimeUnit.MILLISECONDS,queue) ;
poolExecutor.execute(new Runnable() {
@Override
public void run() {
LOGGER.info("running");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
poolExecutor.execute(new Runnable() {
@Override
public void run() {
LOGGER.info("running2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
poolExecutor.shutdown();
while (!poolExecutor.awaitTermination(1,TimeUnit.SECONDS)){
LOGGER.info("線程還在執行。。。");
}
LOGGER.info("main over");
}
使用這個 awaitTermination()
方法的前提需要關閉線程池,如調用了 shutdown()
方法。
調用了 shutdown()
之後線程池會停止接受新任務,並且會平滑的關閉線程池中現有的任務。
(7)管道通信
public static void piped() throws IOException {
//面向於字符 PipedInputStream 面向於字節
PipedWriter writer = new PipedWriter();
PipedReader reader = new PipedReader();
//輸入輸出流建立連接
writer.connect(reader);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("running");
try {
for (int i = 0; i < 10; i++) {
writer.write(i+"");
Thread.sleep(10);
}
} catch (Exception e) {
} finally {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
LOGGER.info("running2");
int msg = 0;
try {
while ((msg = reader.read()) != -1) {
LOGGER.info("msg={}", (char) msg);
}
} catch (Exception e) {
}
}
});
t1.start();
t2.start();
}
Java 雖說是基於內存通信的,但也可以使用管道通信。
需要注意的是,輸入流和輸出流需要首先建立連接。這樣線程 B 就可以收到線程 A 發出的消息了。
實際開發中可以靈活根據需求選擇最適合的線程通信方式。