Java高级篇(四十五)------Java线程之Exchanger

Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据。

当线程A调用Exchange对象的exchange()方法后,他会陷入阻塞状态,直到线程B也调用了exchange()方法,然后以线程安全的方式交换数据,之后线程A和B继续运行

[java]  view plain  copy
  1. public class ThreadLocalTest {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Exchanger<List<Integer>> exchanger = new Exchanger<>();  
  5.         new Consumer(exchanger).start();  
  6.         new Producer(exchanger).start();  
  7.     }  
  8.   
  9. }  
  10.   
  11. class Producer extends Thread {  
  12.     List<Integer> list = new ArrayList<>();  
  13.     Exchanger<List<Integer>> exchanger = null;  
  14.     public Producer(Exchanger<List<Integer>> exchanger) {  
  15.         super();  
  16.         this.exchanger = exchanger;  
  17.     }  
  18.     @Override  
  19.     public void run() {  
  20.         Random rand = new Random();  
  21.         for(int i=0; i<10; i++) {  
  22.             list.clear();  
  23.             list.add(rand.nextInt(10000));  
  24.             list.add(rand.nextInt(10000));  
  25.             list.add(rand.nextInt(10000));  
  26.             list.add(rand.nextInt(10000));  
  27.             list.add(rand.nextInt(10000));  
  28.             try {  
  29.                 list = exchanger.exchange(list);  
  30.             } catch (InterruptedException e) {  
  31.                 // TODO Auto-generated catch block  
  32.                 e.printStackTrace();  
  33.             }  
  34.         }  
  35.     }  
  36. }  
  37.   
  38. class Consumer extends Thread {  
  39.     List<Integer> list = new ArrayList<>();  
  40.     Exchanger<List<Integer>> exchanger = null;  
  41.     public Consumer(Exchanger<List<Integer>> exchanger) {  
  42.         super();  
  43.         this.exchanger = exchanger;  
  44.     }  
  45.     @Override  
  46.     public void run() {  
  47.         for(int i=0; i<10; i++) {  
  48.             try {  
  49.                 list = exchanger.exchange(list);  
  50.             } catch (InterruptedException e) {  
  51.                 // TODO Auto-generated catch block  
  52.                 e.printStackTrace();  
  53.             }  
  54.             System.out.print(list.get(0)+", ");  
  55.             System.out.print(list.get(1)+", ");  
  56.             System.out.print(list.get(2)+", ");  
  57.             System.out.print(list.get(3)+", ");  
  58.             System.out.println(list.get(4)+", ");  
  59.         }  
  60.     }  
  61. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值