Exchanger 的使用

package com.thread.concurrent;

import java.util.concurrent.*;

@SuppressWarnings("all")
public class ExchangerDemo {

    public static void main(String[] args) {
        Exchanger integerExchanger = new Exchanger<>();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new Thread01(integerExchanger));
        executorService.execute(new Thread02(integerExchanger));
        executorService.shutdown();

    }

    static class Thread01 implements Runnable {
        Exchanger exchanger;

        public Thread01(Exchanger exchanger) {
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + "开始执行任务");
                TimeUnit.MILLISECONDS.sleep(6000);
                Object exchange = exchanger.exchange(6);
                System.out.println(exchange+"----");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "任务结束");
        }
    }

    static class Thread02 implements Runnable {
        Exchanger exchanger;
        public Thread02(Exchanger exchanger) {
            this.exchanger = exchanger;
        }
        @Override
        public void run() {
            try {

                System.out.println(Thread.currentThread().getName() + "开始执行任务");
                TimeUnit.MILLISECONDS.sleep(2000);
                //Object exchange = exchanger.exchange(4,2000,TimeUnit.MILLISECONDS);
                Object exchange = exchanger.exchange(4);
                System.out.println(exchange+"=====");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "任务结束");
        }
    }

}

你可能感兴趣的:(java多线程)