Java Concurrency - Exchanger exchanging data between threads

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.

Exchanger application 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 , and two proofreading Excel data, to see if same entry, as shown in the code below.

package pers.zhang.part6;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhang
 * @date 2020/1/21 - 18:00
 *
 * 测试Exchanger
 */
public class ExchangerTest {
    private static final Exchanger<String> exgr = new Exchanger<String>();
    private static ExecutorService threadPool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        threadPool.execute(() -> {
            try {
                String A = "银行流水A";//A录入银行流水数据
                exgr.exchange(A);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        threadPool.execute(() -> {
            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) {
                e.printStackTrace();
            }
        });
        threadPool.shutdown();
    }
}

Output:

A和B数据是否一致:false,A录入的是:银行流水A,B录入是:银行流水B

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 649 original articles · won praise 1877 · Views 230,000 +

Guess you like

Origin blog.csdn.net/cold___play/article/details/104064447