Exchanger

简单说就是一个线程在完成一定的事务后想与另一个线程交换数据

import java.util.concurrent.Exchanger;

public class T3 {
    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(
            new Runnable() {
                @Override
                public void run() {
                    String data1 = "data1111111111";
                    try {
                        System.out.println(Thread.currentThread().getName()+data1+"old");
                        String data2 = exchanger.exchange(data1);
                        System.out.println(Thread.currentThread().getName()+data2+"new");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"t1"
        ).start();

        new Thread(
            new Runnable() {
                @Override
                public void run() {
                    String data1 = "data2222222222";
                    try {
                        System.out.println(Thread.currentThread().getName()+data1);
                        String data2 = exchanger.exchange(data1);
                        System.out.println(Thread.currentThread().getName()+data2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"t2"
        ).start();
    }
}

上一篇:binguan宾馆:MVC:jsp+servlet+javabean


下一篇:java join()方法的作用以及造成死锁的原因