Exchanger兄弟线程间数据信息交换
一、简述
Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据。当线程A调用Exchange对象的exchange()方法后,他会陷入阻塞状态,直到线程B也调用了exchange()方法,然后以线程安全的方式交换数据,之后线程A和B继续运行。
二、代码示例
1 public class ExchangerTest { 2 3 public static void main(String[] args) { 4 Exchanger<String> exchanger = new Exchanger<>(); 5 ExecutorService executorService = Executors.newFixedThreadPool(2); 6 String data = ""; 7 executorService.execute(new Procuder(data, exchanger)); 8 executorService.execute(new Consumer(data, exchanger)); 9 } 10 11 } 12 13 class Procuder implements Runnable{ 14 15 private String data; 16 private Exchanger<String> exchanger; 17 public Procuder(String data,Exchanger<String> exchanger) { 18 this.data = data; 19 this.exchanger = exchanger; 20 } 21 22 @Override 23 public void run() { 24 25 try { 26 for (int i = 0; i < 5; i++) { 27 data = new Random().nextInt(1000)+""; 28 System.out.println("producer"+i+" "+data); 29 Thread.sleep(new Random().nextInt(5)*1000); 30 exchanger.exchange(data); 31 } 32 } catch (InterruptedException e) { 33 e.printStackTrace(); 34 } 35 } 36 37 } 38 39 class Consumer implements Runnable{ 40 41 private String data; 42 private Exchanger<String> exchanger; 43 public Consumer(String data,Exchanger<String> exchanger) { 44 this.data = data; 45 this.exchanger = exchanger; 46 } 47 48 @Override 49 public void run() { 50 51 try { 52 for (int i = 0; i < 5; i++) { 53 data = exchanger.exchange(data); 54 Thread.sleep(new Random().nextInt(5)*1000); 55 System.out.println("Consumer"+i+" "+data); 56 } 57 } catch (InterruptedException e) { 58 e.printStackTrace(); 59 } 60 } 61 62 }
producer0 360 producer1 782 Consumer0 360 producer2 503 Consumer1 782 producer3 367 Consumer2 503 producer4 151 Consumer3 367 Consumer4 151