首页 > 代码库 > Exchanger兄弟线程间数据信息交换
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 datahttp://www.mamicode.com/= ""; 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 =http://www.mamicode.com/ 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 = http://www.mamicode.com/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 =http://www.mamicode.com/ 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 =http://www.mamicode.com/ 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
Exchanger兄弟线程间数据信息交换
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。