Java5的Exchanger同步工具简单实例

package cn.tool;

import java.util.Random;
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 pool=Executors.newCachedThreadPool();
        final Exchanger ex=new Exchanger();
        pool.execute(new Runnable(){
            @Override
            public void run() {
            String data1="liii";
            System.out.println(Thread.currentThread().getName()+"准备把数据"+data1+"交换出去");
            try {
                Thread.sleep(new Random().nextInt(10000));
                // 线程1和线程2随机休息的时间不一样,所以到达exchange的时间不同
                //会等待两个线程都到达exchange时开始交换
                String  data2 = (String) ex.exchange(data1);
                System.out.println(Thread.currentThread().getName()+"换回的数据为:"+data2);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }   

            }

        });

        pool.execute(new Runnable(){
            @Override
            public void run() {
            String data1="dddi";
            System.out.println(Thread.currentThread().getName()+"准备把数据"+data1+"交换出去");
            try {
                Thread.sleep(new Random().nextInt(10000));
                // 线程1和线程2随机休息的时间不一样,所以到达exchange的时间不同
                //会等待两个线程都到达exchange时开始交换
                String  data2 = (String) ex.exchange(data1);
                System.out.println(Thread.currentThread().getName()+"换回的数据为:"+data2);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }   

            }

        });
    }

}
运行结果:
pool-1-thread-1准备把数据liii交换出去
pool-1-thread-2准备把数据dddi交换出去
pool-1-thread-2换回的数据为:liii
pool-1-thread-1换回的数据为:dddi

你可能感兴趣的:(java)