java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java Exchanger数据交换实例

Java多线程编程之使用Exchanger数据交换实例

投稿:junjie

这篇文章主要介绍了Java多线程编程之使用Exchanger数据交换实例,本文直接给出实例代码,需要的朋友可以参考下

用于实现两个人之间的数据交换,每个人在完成一定的事务后想与对方交换数据,第一个先拿出数据的人将一直等待第二个人拿着数据到来时,才能彼此交换数据。

复制代码 代码如下:

package com.ljq.test.thread;
 
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class ExchangerTest {
 
    public static void main(String[] args) {
        
        ExecutorService service = Executors.newCachedThreadPool();
        final Exchanger exchanger = new Exchanger();
        service.execute(new Runnable(){
            public void run() {
                try {             
 
                    String data1 = "张三";
                    System.out.println("线程" + Thread.currentThread().getName() + "正在把数据'" + data1 +"'换出去");
                    Thread.sleep((long)(Math.random()*10000));
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为'" + data2+"'");
                }catch(Exception e){
                    
                }
            } 
        });
        service.execute(new Runnable(){
            public void run() {
                try {             
                    String data1 = "李四";
                    System.out.println("线程" + Thread.currentThread().getName() + "正在把数据'" + data1 +"'换出去");
                    Thread.sleep((long)(Math.random()*10000));                
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为'" + data2 + "'");
                }catch(Exception e){
                    
                }             
            } 
        });   
    }
}

返回结果:

复制代码 代码如下:

线程pool-1-thread-1正在把数据'张三'换出去
线程pool-1-thread-2正在把数据'李四'换出去
线程pool-1-thread-1换回的数据为'李四'
线程pool-1-thread-2换回的数据为'张三'

您可能感兴趣的文章:
阅读全文