Exchanger的使用Demo

package com.interview.javabasic;

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

public class ExchangerDemo
{
    private static Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args)
    {
        ExecutorService service = Executors.newFixedThreadPool(2);
        service.execute(()->{
            try
            {
                String girl  = exchanger.exchange("我是女生");
                System.out.println("女生说:" + girl);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        });
        service.execute(()->{
            try
            {
                System.out.println("要开始了===");
                String boy  = exchanger.exchange("我是男生");
                System.out.println("男生说:" + boy);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        });
    }
}

运行结果

要开始了===
男生说:我是女生
女生说:我是男生

你可能感兴趣的:(笔记)