juc-Exchanger两个线程通信交换数据

Exchanger的使用类,的功能可以使2个线程之间传输数据,它比生产者/消费者模式使用的wait/notify要更加方便

**方法exchange()**阻塞的特性类Exchanger中的exchange()方法具有阻塞的特色,也就是此方法被调用后等待其他线程来取得数据,如果没有其他线程取得数据,则一直阻塞等待。

public class ThreadA extends Thread {
    private Exchanger<String> exchanger;
    public ThreadA(Exchanger<String> exchanger){
        super();
        this.exchanger=exchanger;
    }
    public void run(){
        try {
            System.out.println("线程A中得到线程B的值"+exchanger.exchange("中国人A"));
            System.out.println("A end");
        }catch (Exception e){
            e.fillInStackTrace();
        }
    }
}
public class ThreadB extends Thread {
    private Exchanger<String> exchanger;
    public ThreadB(Exchanger exchanger){
        super();
        this.exchanger=exchanger;
    }
    public void run(){
        try {
            System.out.println("线程B获取线程A的值="+exchanger.exchange("中国人B"));
        }catch (Exception e){
            e.getStackTrace();
        }
    }
}
public class Run {
    public static void main(String[] args) {
        Exchanger<String> exchanger=new Exchanger<String>();
        ThreadA a=new ThreadA(exchanger);
        ThreadB b=new ThreadB(exchanger);
        a.start();
        b.start();
        System.out.println("main end");
    }
}

运行结果
juc-Exchanger两个线程通信交换数据_第1张图片

方法exchange(V x, long timeout, TimeUnit unit)

与超时当调用exchange(V x, long timeout, TimeUnit unit)方法后在指定的时间内没有其他线程获取数据,则出现超时异常。

public class ThreadA extends Thread {
    private Exchanger<String> exchanger;
    public ThreadA(Exchanger<String> exchanger){
        super();
        this.exchanger=exchanger;
    }
    public void run(){
        try {
            System.out.println("在线程A中得到线程B的值"+exchanger.exchange("中国人A",5, TimeUnit.SECONDS));
            System.out.println("A end!");
        }catch (InterruptedException e){
            e.printStackTrace();
        }catch (TimeoutException e){
            e.printStackTrace();
        }
    }
}
public class Run {
    public static void main(String[] args) {
        Exchanger<String> exchanger=new Exchanger<String>();
        ThreadA a=new ThreadA(exchanger);
        a.start();
        System.out.println("main end!");
    }
}

线程会先阻塞,然后5秒中交换数据未成功,抛出异常
运行结果
juc-Exchanger两个线程通信交换数据_第2张图片

你可能感兴趣的:(并发编程)