Java並發編程之代碼實現兩玩傢交換裝備
1 Exchanger 是什麼
JDK 1.5 開始 JUC 包下提供的 Exchanger 類可用於兩個線程之間交換信息。Exchanger 對象可理解為一個包含2個格子的容器,通過調用 exchanger 方法向其中的格子填充信息,當兩個格子中的均被填充信息時,自動交換兩個格子中的信息,然後將交換的信息返回給調用線程,從而實現兩個線程的信息交換。
功能看似簡單,但這在某些場景下是很有用處的,例如遊戲中兩個玩傢交換裝備;交友軟件男女心儀對象匹配。
下面簡單模擬下兩個玩傢交換裝備的場景。
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(); } }
// 輸出結果如下
交易成功,張無忌獲得屠龍刀
交易成功,周芷若獲得倚天劍
2 Exchanger 詳解
Exchager 類可用於兩個線程之間交換信息,如果一個線程調用瞭 Exchanger 對象的 exchange 方法之後,會一直阻塞直到另一個線程來和它交換信息,交換之後的信息返回給調用線程,從而實現兩個線程的信息交換。
Exchager 底層也是使用到瞭自旋和 cas 機制。
註意,如果超過兩個線程調用同一個 Exchanger 對象 exchange 方法時,結果是不可預計的,隻要有2個線程滿足條件瞭,就認為匹配成功並交換信息。而剩下的未能得到配對的線程,則會被阻塞一直等待直到有另一個線程能與它匹配與之配對。
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(); } }
// 輸出結果如下
交易成功,周芷若獲得假的倚天劍
交易成功,成昆獲得屠龍刀
當然,在等待交換信息的線程是可以被中斷的,就比如玩傢在等待交易過程中,突然玩傢下線瞭,那就應該中斷線程等待。
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(); } } } }
// 輸出結果如下
交易成功,張無忌獲得屠龍刀
交易成功,周芷若獲得倚天劍
周芷若: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 還可以設置等待指定時間。比如系統設置玩傢交換裝備匹配時間為60秒,如果超出時間則終止交易。
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 { // 超時時間設置為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(); } }
// 輸出結果如下
交易超時!
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 應用
Exchager 在遺傳算法和管道設計等應用中是非常有用的。比如兩個線程之間交換緩沖區,填充緩沖區的線程在需要時從另一個線程獲得一個剛清空的緩沖區,並將填充的緩沖區傳遞給清空緩沖區的線程。
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(); } }
總結
本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!