java Exchanger
Exchanger 用于两个线程之间交换数据,举例;
package com.hts;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExchangerTest {
class Product implements Runnable{
Exchanger<Integer> exchanger ;
Product(Exchanger<Integer> exchanger ){
this.exchanger = exchanger;
}
@Override
public void run() {
int data;
for(int i = 1;i<11;i++){
data = i;
System.out.println("Product"+i+"交换前:" + data);
try {
data = exchanger.exchange(data);
System.out.println("Product"+i+"交换后:" + data);
System.out.println();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
Exchanger<Integer> exchanger ;
Consumer(Exchanger<Integer> exchanger ){
this.exchanger = exchanger;
}
@Override
public void run() {
int data = 0;
for(int i = 1;i<11;i++){
data = 0;
System.out.println("Consumer"+i+"交换前:" + data);
try {
data = exchanger.exchange(data);
System.out.println("Consumer"+i+"交换后:" + data);
System.out.println();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Exchanger<Integer> exchanger = new Exchanger<>();
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(new ExchangerTest().new Product(exchanger));
executorService.submit(new ExchangerTest().new Consumer(exchanger));
}
}
执行结果:
大概意思就是一个线程交换的数字是从1-10,而另一个线程则每次交换的数据都是0,可以看出这个exchanger.exchange(data);方法是一个阻塞方法,当一个线程等待交换时,一定会等到另一个线程也执行exchanger.exchange(data)同时进行交换,交换后才会继续往下执行。