生产者和消费者模型需要一个公共操作区域进行数据的保存与获取,在JUC中专门提供了一个交换区域的程序类:java.util.concurrent.Exchanger类。
1、使用Exchanger实现数据交换的例子:
package com.mydemo;
import java.util.concurrent.Exchanger;
public class JUCDemo {
public static void main(String[] args) {
// 定义交换空间
Exchanger<String> exchanger = new Exchanger<>();
// 结束标记
boolean isEnd = false;
new Thread(()->{
String data = null;
try {
// 生产数据
for(int i = 0; i < 5; i++){
data = "test" + i;
System.out.println("【Producer-BEFORE - " + i + "】" + data);
Thread.sleep(1000);
// 保存数据
exchanger.exchange(data);
System.out.println("【Producer-AFTER - " + i + "】" + data);
}
}catch (Exception e){}finally {
}
}, "【Producer】信息生产者").start();
new Thread(()->{
String data = null;
try {
// 消费数据
while(!isEnd){
System.out.println("【Consumer-BEFORE】" + data);
Thread.sleep(2000);
// 获取数据
data = exchanger.exchange(null);
System.out.println("【Consumer-AFTER】" + data);
}
}catch (Exception e){}finally {
}
}, "【Consumer】信息消费者").start();
}
}