Art Java concurrent programming (17) Exchanger

Exchanger exchanging data between threads

Exchanger (exchanger) is a class tool for collaboration between threads. Exchanger for exchanging data between threads. It provides a synchronization point, in this synchronization point, two threads can exchange data with each other. These two threads to exchange data exchange method, if the first thread to execute exchange () method, which has been waiting for a second thread also performs exchange method, when two threads have reached the synchronization point, these two threads data can be exchanged, passing this thread produced data to each other.

Scenarios

Exchanger can be used for genetic algorithm, genetic algorithm was to elect two people as a mate, this time the two will exchange data and using rules drawn two cross mating results. Exchanger can also be used for proof-reading, for example, we will need a paper bank water by artificial means water entry into electronic banking, in order to avoid mistakes, the two men were using AB Kong entry, then entered into Excel, the system needs to load both Excel , proofreading and two Excel data to see if the same entry.

public class ExchangerTest {
    private static final Exchanger<String> exgr = new Exchanger<String>();
    private static Executor ServicethreadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String A = "银行流水A"; // A录入银行流水数据 
                    exgr.exchange(A);
                } catch (InterruptedException e) {
                }
            }
        });
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String B = "银行流水B"; // B录入银行流水数据 
                    String A = exgr.exchange("B");
                    System.out.println("A和B数据是否一致:" + A.equals(B) + ",A录入的是:"
                            + A + ",B录入是:" + B);
                } catch (InterruptedException e) {
                }
            }
        });
        threadPool.shutdown();
    }
}

If two threads have a no exchange () method executes, it will have to wait a long time if you are concerned there are special circumstances occur, to avoid the waits can use the exchange (V x, longtimeout, TimeUnit unit) setting maximum waiting.

Published 24 original articles · won praise 1 · views 534

Guess you like

Origin blog.csdn.net/qq_45366515/article/details/105267221