Java Exchanger的用法

Java提供了线程间交换数据的相关类,使用起来也很方便。线程完成一定的数据后再与其他线程进行数据交换。
首先导包:

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

使用代码如下:

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 = "data1";
                    System.out.println("线程" + Thread.currentThread().getName() + 
                    "正在把数据" + data1 +"换出去");
                    Thread.sleep((long)(Math.random()*1000));
                    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 = "data2";
                    System.out.println("线程" + Thread.currentThread().getName() + 
                    "正在把数据" + data1 +"换出去");
                    Thread.sleep((long)(Math.random()*1000));                    
                    String data2 = (String)exchanger.exchange(data1);
                    System.out.println("线程" + Thread.currentThread().getName() + 
                    "换回的数据为" + data2);
                }catch(Exception e){
                }                
            }    
        });        
    }

运行结果:

Java Exchanger的用法_第1张图片

你可能感兴趣的:(Java基础)