Exchanger兄弟线程间数据信息交换

一、简述

  Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据。当线程A调用Exchange对象的exchange()方法后,他会陷入阻塞状态,直到线程B也调用了exchange()方法,然后以线程安全的方式交换数据,之后线程A和B继续运行。

二、代码示例

 public class ExchangerTest {

     public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
ExecutorService executorService = Executors.newFixedThreadPool(2);
String data = "";
executorService.execute(new Procuder(data, exchanger));
executorService.execute(new Consumer(data, exchanger));
} } class Procuder implements Runnable{ private String data;
private Exchanger<String> exchanger;
public Procuder(String data,Exchanger<String> exchanger) {
this.data = data;
this.exchanger = exchanger;
} @Override
public void run() { try {
for (int i = 0; i < 5; i++) {
data = new Random().nextInt(1000)+"";
System.out.println("producer"+i+" "+data);
Thread.sleep(new Random().nextInt(5)*1000);
exchanger.exchange(data);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} } class Consumer implements Runnable{ private String data;
private Exchanger<String> exchanger;
public Consumer(String data,Exchanger<String> exchanger) {
this.data = data;
this.exchanger = exchanger;
} @Override
public void run() { try {
for (int i = 0; i < 5; i++) {
data = exchanger.exchange(data);
Thread.sleep(new Random().nextInt(5)*1000);
System.out.println("Consumer"+i+" "+data);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
producer0 360
producer1 782
Consumer0 360
producer2 503
Consumer1 782
producer3 367
Consumer2 503
producer4 151
Consumer3 367
Consumer4 151
上一篇:Ajax请求接口加密研究(针对网页前端的接口安全加密机制研究)


下一篇:form-validation--表单验证插件