zoukankan      html  css  js  c++  java
  • Java核心-多线程(7)-并发控制器-Exchanger交换器

    1.基本概念
    Exchanger,从名字上理解就是交换。Exchanger用于在两个线程之间进行数据交换,注意也只能在两个线程之间进行数据交换。
    线程会阻塞在Exchanger的exchange方法上,直到另外一个线程也到了同一个Exchanger的exchange方法时,二者进行数据交换,
    然后两个线程继续执行自身相关的代码。
    2.抽像模型
    线程同步、线程通信
    3.使用场景
    两个线程之间交换数据(没有更好的例子了)
    4.Exchanger使用api

         Exchanger<E> exchanger = new Exchanger<E>();
    
        exchanger.exchange(num); //当前执行线程等待另一个线程执行此行代码,完成变量num的交换
    

    5.示例

        private static class ExchangeThread extends Thread{
    		private Integer num;
    		private Exchanger<Integer> exchange;
    		private int sleepTime;
    		public ExchangeThread(Integer num, Exchanger<Integer> exchange, int sleepTime) {
    			super();
    			this.num = num;
    			this.exchange = exchange;
    			this.sleepTime = sleepTime;
    		}
    		@Override
    		public void run() {
    			System.out.println(this.getName() + "线程开始工作了,当前号码是" + num + ",当前时间" + System.currentTimeMillis());
    			try {
    				Thread.sleep(sleepTime);
    				num = exchange.exchange(num);
    				System.out.println(this.getName() + "线程开始完成了工作,当前号码是" + num + ",当前时间" + System.currentTimeMillis());
    
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			
    			super.run();
    		}
    	}
    
    执行结果
    Thread-1线程开始工作了,当前号码是2,当前时间1555346410059
    Thread-0线程开始工作了,当前号码是1,当前时间1555346410059
    Thread-1线程开始完成了工作,当前号码是1,当前时间1555346418065
    Thread-0线程开始完成了工作,当前号码是2,当前时间1555346418065
    
  • 相关阅读:
    iptables dnat不通
    os.system()和os.popen()
    mysql登录提示ERROR 1524 (HY000): Plugin 'unix_socket' is not loaded解决方法
    SpringBoot之web开发
    基于MQ的分布式事务解决方案
    Docker核心技术
    [Java]Object有哪些公用方法?
    zookeeper
    单例模式的几种实现方式及优缺点
    并发编程之Synchronized原理
  • 原文地址:https://www.cnblogs.com/leeethan/p/10714410.html
Copyright © 2011-2022 走看看