package com.duchong.concurrent;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger; /**
* Exchanger用于进行线程间的数据交换。它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据。这两个线程通过exchange方法交换数据,
* 如果第一个线程先执行exchange()方法,它会一直等待第二个线程也执行exchange方法,当两个线程都到达同步点时,这两个线程就可以交换数据,
* 将本线程生产出来的数据传递给对方。
* @author DUCHONG
* @since 2019-09-18 10:20
**/
public class ExchangeDemo { static final Exchanger<List<String>> exchanger = new Exchanger<>(); public static void main(String[] args) { new Thread(()->putDataA()).start(); new Thread(()->putDataB()).start(); } public static void putDataA(){ System.out.println("putDataA:");
String name = Thread.currentThread().getName();
System.out.println(name);
try {
List<String> list = new ArrayList<>();
list.add(name+"---a1");
list.add(name+"---a2"); list = exchanger.exchange(list); for(String data:list){
System.out.println("putDataA:"+data);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} public static void putDataB(){ System.out.println("putDataB:");
String name = Thread.currentThread().getName();
System.out.println(name);
try { List<String> list = new ArrayList<>();
list.add(name+"---b1");
list.add(name+"---b2");
list.add(name+"---b3");
list.add(name+"---b4");
list.add(name+"---b5"); Thread.sleep(2000);
list = exchanger.exchange(list); for(String data:list){
System.out.println("putDataB:"+data);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} }

Exchanger实现线程间数据交换-LMLPHP

05-27 07:37