摘要:JDK 1.5 开始 JUC 包下提供的 Exchanger 类可用于两个线程之间交换信息。 本文分享自华为云社区《一行Java代码实现两玩家交换装备【并发编程】》,作者:陈皮的JavaLib 。
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();
}
}
点击关注,第一时间了解华为云新鲜技术~
|