java Concurrent Programming - chicken rib tool -- exchange thread data Exchanger

Posted by gardner1 on Mon, 18 May 2020 16:10:40 +0200

preface

As one of the tools of java Concurrent Programming, the exchange only supports data exchange between two threads. When thread A needs to exchange its own data with thread B internally, after calling exchange(), it will automatically block and wait for the other thread's data to arrive, and then exchange. It uses CAS mechanism to realize data exchange.


Simple validation usage

public class UseExchange {
    private static final Exchanger<Set<String>> exchange = new Exchanger<Set<String>>();

    public static void main(String[] args) {

        new Thread(new Runnable() {
            @Override
            public void run() {
               Set<String> setA = new HashSet<String>();//Container for data
                try {
                   /*Add data*/
                   setA.add("a");
                    setA.add("b");
                    setA.add("c");

                   Set<String> setB = exchange.exchange(setA);//Exchange set
                   /*Process the exchanged data*/
                    System.out.println("Printing setA and setB Data after exchange:");
                    for (String s : setB){
                        System.out.println(s);
                    }
                    System.out.println("=============In exchange setB================");
                } catch (InterruptedException e) {
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
               Set<String> setB = new HashSet<String>();//Container for data
                try {
                   /*Add data*/
                   setB.add("d");
                   setB.add("e");
                    setB.add("f");

                    Set<String>    setA = exchange.exchange(setB);//Exchange set
                   /*Process the exchanged data*/
                    System.out.println("Printing setB and setA Data after exchange:");
                    for (String s : setA){
                        System.out.println(s);
                    }
                    System.out.println("=============In exchange setA================");
                } catch (InterruptedException e) {
                }
            }
        }).start();
    }
}


Output results


Topics: Programming Java