Multithreaded Learning Exchange

Exchange data exchange between multiple threads

Use exchange to interact with data between two threads. The threads must appear in pairs, otherwise the threads will always be in a waiting state, or set a timeout. The data interaction between multiple threads is random


    final Exchanger<String> objectExchanger = new Exchanger<>();
        new Thread(() -> {
    
    
            try {
    
    
                System.out.println("我有10块钱, 我去超市买苹果");
                Object exchange = objectExchanger.exchange("10RMB");
                System.out.println("买到了" + exchange.toString());
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
    
    
            try {
    
    
                System.out.println("超市中有苹果!");
                Object exchange = objectExchanger.exchange("苹果");
                System.out.println("出售了苹果,收到" + exchange.toString());
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }).start();
    }

I have 10 yuan. I go to the supermarket to buy apples
. There are apples in the supermarket!
I sold apples and
bought apples with 10RMB

Very easy to use

Guess you like

Origin blog.csdn.net/xiaodujava/article/details/101529428