Java线程--Exchanger使用
原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/11868576.html
Java线程--Exchanger使用:
Exchanger 是用来交换2个线程之间的消息的, 超过2个线程则是随机发送消息, 不保证可靠性!
public static void main(String[] args) { /** * 两个线程间的数据交换 */ Exchanger exchanger = new Exchanger(); ExecutorService service1 = Executors.newSingleThreadExecutor(); service1.execute(new Runnable() { @Override public void run() { try { Thread.sleep(3000); System.out.println("子线程:"+Thread.currentThread().getName()+"收到的消息是: " + exchanger.exchange("你好这里是线程1")); } catch (InterruptedException e) { e.printStackTrace(); } } }); service1.shutdown(); ExecutorService service2 = Executors.newSingleThreadExecutor(); service2.execute(new Runnable() { @Override public void run() { try { Thread.sleep(3000); System.out.println("子线程:"+Thread.currentThread().getName()+"收到的消息是: " + exchanger.exchange("你好这里是线程2")); } catch (InterruptedException e) { e.printStackTrace(); } } }); service2.shutdown(); }
打印:
子线程:pool-1-thread-1收到的消息是: 你好这里是线程2
子线程:pool-2-thread-1收到的消息是: 你好这里是线程1