In Java: Can Exchanger only exchange data between two threads?

Conclusion: Can Exchanger only exchange data between two threads? What happens to those three calls to the exchange method of the same instance? The answer is that only the first two threads will exchange data, and the third thread will enter a blocked state.

Above code:


public class ExchangerDemo {
    public static void main(String[] args) throws InterruptedException {
        Exchanger<String> exchanger = new Exchanger<>();
        new Thread(() -> {
            try {
                System.out.println("这是线程A,得到了另⼀个线程的数据:"
                        + exchanger.exchange("这是来⾃线程A的数据"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        System.out.println("这个时候线程A是阻塞的,在等待线程B的数据");
        Thread.sleep(1000);
        new Thread(() -> {
            try {
                System.out.println("这是线程B,得到了另⼀个线程的数据:"
                        + exchanger.exchange("这是来⾃线程B的数据"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread.sleep(1000);
        new Thread(() -> {
            try {
                System.out.println("这是线程C,得到了另⼀个线程的数据:"
                        + exchanger.exchange("这是来⾃线程X的数据"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

output:

At this time, thread A is blocked, waiting for the data of thread B.
This is thread B, which got data from another thread: this is the data from thread A. This
thread A got data from another thread: this is the data from thread B.

Guess you like

Origin blog.csdn.net/liuruiaaa/article/details/130897317
Recommended