Exchanger(不同线程之间的数据交换)
- 方法是exchange()
public class Demo { public static void main(String[] args) { ExecutorService threadPool = Executors.newCachedThreadPool(); Exchanger<String> exchanger = new Exchanger<>(); //绑匪 用美女交换钱 threadPool.execute(new Runnable() { @Override public void run() { try { String content = exchanger.exchange("美女"); System.out.println("绑匪得到了"+content); } catch (InterruptedException e) { e.printStackTrace(); } } }); //家属 用钱交换会美女 threadPool.execute(new Runnable() { @Override public void run() { try { String content = exchanger.exchange("100万"); System.out.println("家属解救了"+content); } catch (InterruptedException e) { e.printStackTrace(); } } }); threadPool.shutdown(); } }