<返回更多

JAVA多线程-Exchanger

2020-07-28    
加入收藏

JAVA.util.concurrent.Exchanger类代表了两个线程在一个集合点可以交互数据。下面描述了一下机制:

 

JAVA多线程-Exchanger

两个线程通过Exchanger 正在交换对象数据

交换对象数据是通过 exchange()方法,下面是例子:

Exchanger exchanger = new Exchanger();
ExchangerRunnable exchangerRunnable1 =  
  new ExchangerRunnable(exchanger, "A"); ExchangerRunnable exchangerRunnable2 =        new ExchangerRunnable(exchanger, "B"); new Thread(exchangerRunnable1).start();new Thread(exchangerRunnable2).start();

 

ExchangerRunnable代码:

public class ExchangerRunnable implements Runnable{   
  Exchanger exchanger = null;    
	Object    object    = null;     
	public ExchangerRunnable(Exchanger exchanger, Object object) {        
    	this.exchanger = exchanger;        
    	this.object = object;    
  }     
	public void run() {       
    	try {            
        Object previous = this.object;             
        this.object = this.exchanger.exchange(this.object);             
        System.out.println(Thread.currentThread().getName() +    " exchanged " + previous + " for " + this.object   );      
      } catch (InterruptedException e) {            
        e.printStackTrace();        
      }   
  }
}

 

执行结果:

Thread-0 exchanged A for BThread-1 exchanged B for A

 

参考翻译:http://tutorials.jenkov.com/java-util-concurrent/exchanger.html

声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>