线程之间如何交换数据?
JUC中的Exchanger
java.util.concurrent.Exchanger
实现了两个线程之间交换数据
交换器类Exchanger
方法 | 说明 |
---|---|
V exchange(V x) | 交换数据,没有线程交换就一直阻塞 |
V exchange(V x, long timeout, TimeUnit unit) | 在指定时间内没有线程交换,就抛出超时异常 |
简单测试exchange(V x)
public class Test1 {
//创建交换器类的实例
static Exchanger exchanger = new Exchanger();
public static void main(String[] args) {
new Thread(() -> {
Object data = "AAA";
System.out.println(Thread.currentThread().getName() + ":" + data);
//交换数据
try {
data = exchanger.exchange(data);
System.out.println(Thread.currentThread().getName() + ":" + data);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
new