目标:两个线程进行数据交换
exchange
- exchange只能用于两个线程进行数据交换,它的交换速率是高效的
- exchanger.exchange(object obj):这个方法会阻塞,直到另一个线程也同样调用这个方法进行数据交换,当然也可以使用timeout避免阻塞过长时间。
代码实现:
package com.miracle.study.concurrent;
import java.util.concurrent.Exchanger;
/**
* @author Miracle
* @date 2021/4/14 17:47
*/
public class ExchangeTest {
public static void main(String[] args) throws InterruptedException {
Exchanger exchanger = new Exchanger();
new Thread(() ->{
var data = "test01";
String exchange = null;
try {
exchange = (String) exchanger.exchange(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + ":" + data);
System.out.println(Thread.currentThread() + ":" + exchange);
}).start();
new Thread(() ->{
var data = "test02";
String exchange = null;
try {
exchange = (String) exchanger.exchange(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread() + ":" + data);
System.out.println(Thread.currentThread() + ":" + exchange);
}).start();
Thread.sleep(1000);
}
}