Exchanger一个小demo

java.util.concurrent*包中的Exchanger类可用于两个线程之间交换信息

可简单地将Exchanger对象理解为一个包含两个格子的容器,通过exchanger方法可以向两个格子中填充信息。当两个格子中的均被填充时,该对象会自动将两个格子的信息交换,然后返回给线程,从而实现两个线程的信息交换。

package com.indi.wzl.Lock;

import java.util.Random;
import java.util.concurrent.Exchanger;

/**
 * 1 Exchanger中的public V exchange(V x)方法被调用后等待另一个线程到达交换点(如果当前线程没有被中断),
 * 然后将已知的对象传给它,返回接收的对象。
 * 2 交换的线程需要是偶数,不能是基数,否则就会有线程在等待交换一直阻塞。
 *
 * @Auther: zonglin_wu
 * @Date: 2020/2/9 18:56
 * @Description:
 */
public class ExchangerTest {

    public class Car extends Thread {
        private Exchanger<String> exchanger;

        public Car(Exchanger<String> exchanger) {
            super("car");
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try {
                String name =Thread.currentThread().getName();
                System.out.println(name + ": " + exchanger.exchange(name));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public class Bike extends Thread {
        private Exchanger<String> exchanger;

        public Bike(Exchanger<String> exchanger) {
            super("bike");
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            try {
                String name =Thread.currentThread().getName();
                System.out.println(name + ": " + exchanger.exchange(name));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Exchanger<String> exchanger = new Exchanger<>();
        ExchangerTest exchangerTest = new ExchangerTest();
        Car car = exchangerTest.new Car(exchanger);
        Car car2 = exchangerTest.new Car(exchanger);
        Bike bike = exchangerTest.new Bike(exchanger);
        Bike bike2 = exchangerTest.new Bike(exchanger);
        car2.setName("car2");
        bike2.setName("bike2");
        car.start();
        bike.start();
        car2.start();
        bike2.start();
        System.out.println("Main end!");
    }

}

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