1 Exchanger 是什么
JDK 1.5 開始 JUC 包下提供的 Exchanger 類可用于兩個線程之間交換信息。Exchanger 對象可理解為一個包含2個格子的容器,通過調(diào)用 exchanger 方法向其中的格子填充信息,當兩個格子中的均被填充信息時,自動交換兩個格子中的信息,然后將交換的信息返回給調(diào)用線程,從而實現(xiàn)兩個線程的信息交換。
功能看似簡單,但這在某些場景下是很有用處的,例如游戲中兩個玩家交換裝備;交友軟件男女心儀對象匹配。
下面簡單模擬下兩個玩家交換裝備的場景。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package com.chenpi; import java.util.concurrent.Exchanger; /** * @Description * @Author 陳皮 * @Date 2021/7/11 * @Version 1.0 */ public class ChenPiMain { public static void main(String[] args) throws InterruptedException { Exchanger<String> exchanger = new Exchanger<>(); new Thread(() -> { String str = null ; try { str = exchanger.exchange( "屠龍刀" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "周芷若" ).start(); new Thread(() -> { String str = null ; try { str = exchanger.exchange( "倚天劍" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "張無忌" ).start(); } } |
// 輸出結(jié)果如下
交易成功,張無忌獲得屠龍刀
交易成功,周芷若獲得倚天劍
2 Exchanger 詳解
Exchager 類可用于兩個線程之間交換信息,如果一個線程調(diào)用了 Exchanger 對象的 exchange 方法之后,會一直阻塞直到另一個線程來和它交換信息,交換之后的信息返回給調(diào)用線程,從而實現(xiàn)兩個線程的信息交換。
Exchager 底層也是使用到了自旋和 cas 機制。
注意,如果超過兩個線程調(diào)用同一個 Exchanger 對象 exchange 方法時,結(jié)果是不可預(yù)計的,只要有2個線程滿足條件了,就認為匹配成功并交換信息。而剩下的未能得到配對的線程,則會被阻塞一直等待直到有另一個線程能與它匹配與之配對。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
package com.chenpi; import java.util.concurrent.Exchanger; /** * @Description * @Author 陳皮 * @Date 2021/7/11 * @Version 1.0 */ public class ChenPiMain { public static void main(String[] args) { Exchanger<String> exchanger = new Exchanger<>(); new Thread(() -> { String str = null ; try { str = exchanger.exchange( "屠龍刀" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "周芷若" ).start(); new Thread(() -> { String str = null ; try { str = exchanger.exchange( "倚天劍" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "張無忌" ).start(); new Thread(() -> { String str = null ; try { str = exchanger.exchange( "假的倚天劍" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "成昆" ).start(); } } |
// 輸出結(jié)果如下
交易成功,周芷若獲得假的倚天劍
交易成功,成昆獲得屠龍刀
當然,在等待交換信息的線程是可以被中斷的,就比如玩家在等待交易過程中,突然玩家下線了,那就應(yīng)該中斷線程等待。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package com.chenpi; import java.lang.Thread.State; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Exchanger; /** * @Description * @Author 陳皮 * @Date 2021/7/11 * @Version 1.0 */ public class ChenPiMain { public static void main(String[] args) throws InterruptedException { Exchanger<String> exchanger = new Exchanger<>(); List<Thread> threads = new ArrayList<>( 3 ); Thread thread1 = new Thread(() -> { String str = null ; try { str = exchanger.exchange( "屠龍刀" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "周芷若" ); threads.add(thread1); Thread thread2 = new Thread(() -> { String str = null ; try { str = exchanger.exchange( "倚天劍" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "張無忌" ); threads.add(thread2); Thread thread3 = new Thread(() -> { String str = null ; try { str = exchanger.exchange( "假的屠龍刀" ); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); }, "成昆" ); threads.add(thread3); for (Thread thread : threads) { thread.start(); } // 等待5秒 Thread.sleep( 5000 ); for (Thread thread : threads) { System.out.println(thread.getName() + ":" + thread.getState()); // 如果還在阻塞等待則中斷線程 if (thread.getState() == State.WAITING) { thread.interrupt(); } } } } |
// 輸出結(jié)果如下
交易成功,張無忌獲得屠龍刀
交易成功,周芷若獲得倚天劍
周芷若:TERMINATED
張無忌:TERMINATED
成昆:WAITING
交易成功,成昆獲得null
java.lang.InterruptedException
at java.util.concurrent.Exchanger.exchange(Exchanger.java:568)
at com.chenpi.ChenPiMain.lambda$main$2(ChenPiMain.java:47)
at java.lang.Thread.run(Thread.java:748)
上面演示的是線程如果等不到另一個線程和它交換信息,則會一直等待下去。其實 Exchanger 還可以設(shè)置等待指定時間。比如系統(tǒng)設(shè)置玩家交換裝備匹配時間為60秒,如果超出時間則終止交易。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package com.chenpi; import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * @Description * @Author 陳皮 * @Date 2021/7/11 * @Version 1.0 */ public class ChenPiMain { public static void main(String[] args) { Exchanger<String> exchanger = new Exchanger<>(); new Thread(() -> { try { // 超時時間設(shè)置為5秒 String str = exchanger.exchange( "屠龍刀" , 5 , TimeUnit.SECONDS); System.out.println( "交易成功," + Thread.currentThread().getName() + "獲得" + str); } catch (TimeoutException e) { System.out.println( "交易超時!" ); e.printStackTrace(); } catch (InterruptedException e) { System.out.println( "交易異常終止" ); e.printStackTrace(); } }, "周芷若" ).start(); } } |
// 輸出結(jié)果如下
交易超時!
java.util.concurrent.TimeoutException
at java.util.concurrent.Exchanger.exchange(Exchanger.java:626)
at com.chenpi.ChenPiMain.lambda$main$0(ChenPiMain.java:22)
at java.lang.Thread.run(Thread.java:748)
3 Exchanger 應(yīng)用
Exchager 在遺傳算法和管道設(shè)計等應(yīng)用中是非常有用的。比如兩個線程之間交換緩沖區(qū),填充緩沖區(qū)的線程在需要時從另一個線程獲得一個剛清空的緩沖區(qū),并將填充的緩沖區(qū)傳遞給清空緩沖區(qū)的線程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package com.chenpi; import java.awt.image.DataBuffer; import java.util.concurrent.Exchanger; /** * @Description * @Author 陳皮 * @Date 2021/7/11 * @Version 1.0 */ public class ChenPiMain { Exchanger<DataBuffer> exchanger = new Exchanger<DataBuffer>(); DataBuffer initialEmptyBuffer = ... a made-up type DataBuffer initialFullBuffer = ... class FillingLoop implements Runnable { public void run() { DataBuffer currentBuffer = initialEmptyBuffer; try { while (currentBuffer != null ) { addToBuffer(currentBuffer); if (currentBuffer.isFull()) { currentBuffer = exchanger.exchange(currentBuffer); } } } catch (InterruptedException ex) { ...handle ...} } } class EmptyingLoop implements Runnable { public void run() { DataBuffer currentBuffer = initialFullBuffer; try { while (currentBuffer != null ) { takeFromBuffer(currentBuffer); if (currentBuffer.isEmpty()) { currentBuffer = exchanger.exchange(currentBuffer); } } } catch (InterruptedException ex) { ...handle ...} } } void start() { new Thread( new FillingLoop()).start(); new Thread( new EmptyingLoop()).start(); } } |
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注服務(wù)器之家的更多內(nèi)容!
原文鏈接:https://blog.csdn.net/chenlixiao007/article/details/120261330