例子很简单 Exchanger可以理解为消息队列或者说是一个通信管道,从一边拿到消息,另外一边进行消费。
不过这个是同步实现的,消费者在exchange之前,生产者一直处于等待状态,而不是一直生产。
代码如下:
package exchange; import java.util.concurrent.Exchanger; public class ExchangerDemo { final static Exchanger<String> exchanger = new Exchanger<>(); //生产者 static class Producer extends Thread { private Exchanger<String> exchanger; public Producer(Exchanger<String> exchanger) { this.exchanger = exchanger; } public void run() { for (int i = 1; i <= 100; i++) { try { String message = "有价值的消息" + i; System.out.println("生产者准备发送:" + message); String result = exchanger.exchange(message); System.out.println("生产者收到:"+result); } catch (InterruptedException e) { e.printStackTrace(); } } } } //消费者 static class Costomer extends Thread { private Exchanger<String> exchanger; public Costomer(Exchanger<String> exchanger) { this.exchanger = exchanger; } public void run() { //消费者 int count = 1; while (true){ String message = "消费者收到第"+(count++) + "条消息"; try { Thread.sleep(100); String exchange = exchanger.exchange(message); System.out.println(message + ",消息内容为:" + exchange); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new Producer(exchanger).start(); new Costomer(exchanger).start(); } }