演示Exchange用法


import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Exchanger;


/**
* 类说明:演示Exchange用法
*/
public class UseExchange {
    private static final Exchanger> exchange = new Exchanger>();


    public static void main(String[] args) {


        new Thread(new Runnable() {
            @Override
            public void run() {
                Set setA = new HashSet();//存放数据的容器
                try {
                    /*添加数据
                     * set.add(.....)
                     * */
                    setA.add("A");
                    setA = exchange.exchange(setA);//交换set
                    /*处理交换后的数据*/


                    Iterator iterator = setA.iterator();
                    while (iterator.hasNext()) {
                        System.out.println("A::"+iterator.next());
                    }
                } catch (InterruptedException e) {
                }
            }
        }).start();


        new Thread(new Runnable() {
            @Override
            public void run() {
                Set setB = new HashSet();//存放数据的容器
                try {
                    /*添加数据
                     * set.add(.....)
                     * set.add(.....)
                     * */
                    setB.add("B");
                    setB = exchange.exchange(setB);//交换set
                    /*处理交换后的数据*/
                    Iterator iterator = setB.iterator();
                    while (iterator.hasNext()) {
                        System.out.println("B::"+iterator.next());
                    }
                } catch (InterruptedException e) {
                }
            }
        }).start();


    }


}

 

你可能感兴趣的:(演示Exchange用法)