Exchanger的使用

/ 多线程 / 没有评论 / 341浏览

Exchanger的作用是可以用来进行线程间数据的交换。线程可以调用Exchanger中的exchange()方法来交换数据。只有两个线程都调用了exchange()方法数据才会交换,如果只有一个线程执行exchange()方法,那么当前线程就会一直等待,直到有其它线程执行exchange()方法时,线程才会恢复。

public class Test {
public static void main(String[] args) throws InterruptedException {
Exchanger<String> exchanger = new Exchanger<String>();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
String msg = "task1";
for (int i = 3; i > 0; i--) {
System.out.println(String.format("计时:%s\tthread: %s", i, Thread.currentThread().getName()));
Thread.sleep(1000);
}
String thread2 = exchanger.exchange(msg);
System.out.println(String.format("thread2: %s\tthread", thread2, Thread.currentThread().getName()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
String msg = "task1";
for (int i = 5; i > 0; i--) {
System.out.println(String.format("计时:%s\tthread: %s", i, Thread.currentThread().getName()));
Thread.sleep(1000);
}
String thread1 = exchanger.exchange(msg);
System.out.println(String.format("thread1: %s\tthread", thread1, Thread.currentThread().getName()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
}
}
计时:5	thread: Thread-1
计时:3	thread: Thread-0
计时:2	thread: Thread-0
计时:4	thread: Thread-1
计时:1	thread: Thread-0
计时:3	thread: Thread-1
计时:2	thread: Thread-1
计时:1	thread: Thread-1
thread1: task1	thread
thread2: task1	thread

我们分析一下输出信息。当线程启动后首先执行循环,当线程1的循环执行完时,没有直接执行后面的语句而是当前线程暂停了,原因就是因为我们调用了exchange()方法,当调用exchange()方法时,必须等待其它线程也调用exchange()方法否则当前线程阻塞,也就是会一直等待。当线程二执行完循环调用exchange()方法时,线程一恢复执行,并获取到了线程二的信息,并输出。线程二的执行过程也是如此。也就是说用Exchanger中的exchange()方法可以使线程间通信并互相交换信息。在日常开发中可以用Exchanger类的exchange()方法处理数据校验的工作。