Exchanger类中的exchange(String x) 方法具有阻塞的特点,也就是说此方法被调用后等待其他线程来获取数据,如果没有其他线程取得数据,则就会一直阻塞等待下去。
Exchanger类中的exchange(String x, long timeout, TimeUnit unit)查看官方API可知这个方法的作用是在制定的时间内没有其他线程获取数据,则会抛出异常
接下来我们来一一用代码的方式进行验证:
1,创建一个工程
2,因为是解决线程间的通信问题所有需要创建一个类继承Thread(我这里的类名是testThread1)代码如下
package cn.wxz;
import java.util.concurrent.Exchanger;
public class testThread1 extends Thread {
private Exchanger< String> exchanger;
public testThread1( Exchanger< String> exchanger){
this.exchanger=exchanger;
}
@Override
public void run() {
super.run();
try {
System.out.println("我是testThread1线程我在这想要获取到testThread2线程传递过来的值="+exchanger.exchange("我是testThread1"));
System.out.println("啦啦啦,执行结束了");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3,创建一个测试类(我这里的类名是Test)代码如下
package cn.wxz;
import java.util.concurrent.Exchanger;
public class Test {
public static void main(String[] args) {
Exchanger exchanger = new Exchanger();
testThread1 testThread1 = new testThread1(exchanger);
testThread1.start();
System.out.println("主函数类已经执行结束了...........");
}
}
4,运行结果如下:
控制台只打印了Test类中的打印语句,而testThread1类中的打印语句没有执行,即一直处于阻塞等待状态,因为已经调用了Exchanger类中的exchange(String x)方法而没有其他线程取得数据,即一直处于阻塞等待状态。
5,接下来验证其他线程取得数据成功,再创建一个线程类testThread2,代码如下
package cn.wxz;
import java.util.concurrent.Exchanger;
public class testThread2 extends Thread {
private Exchanger< String> exchanger;
public testThread2( Exchanger< String> exchanger){
this.exchanger=exchanger;
}
@Override
public void run() {
super.run();
try {
System.out.println("我是testThread2线程我在这想要获取到testThread1线程传递过来的值="+exchanger.exchange("我是testThread2"));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
6,修改后的Test类代码如下:
package cn.wxz;
import java.util.concurrent.Exchanger;
public class Test {
public static void main(String[] args) {
Exchanger exchanger = new Exchanger();
testThread1 testThread1 = new testThread1(exchanger);
testThread2 testThread2 = new testThread2(exchanger);
testThread1.start();
testThread2.start();
System.out.println("主函数类已经执行结束了...........");
}
}
通过控制台打印语句可知,线程间通迅成功
8,来验证第二个方法,接下来我们只需要把testThread1类代码修改成如下
package cn.wxz;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
public class testThread1 extends Thread {
private Exchanger exchanger;
public testThread1(Exchanger exchanger) {
this.exchanger = exchanger;
}
@Override
public void run() {
super.run();
try {
System.out.println("我是testThread1线程我在这想要获取到testThread2线程传递过来的值="
+ exchanger.exchange("我是testThread1", 2, TimeUnit.SECONDS));
System.out.println("啦啦啦,执行结束了");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
9,Test类修改成如下
package cn.wxz;
import java.util.concurrent.Exchanger;
public class Test {
public static void main(String[] args) {
Exchanger exchanger = new Exchanger();
testThread1 testThread1 = new testThread1(exchanger);
testThread1.start();
System.out.println("主函数类已经执行结束了...........");
}
}
10,运行结果如下