?使用到的是Exchanger<V> 类,在java.util.concurrent 包中。使用的时候需要指定交换的类型。 ?调用Exchanger 类对象的exchange(V x) 方法,两个线程都传入要交换的数据 v 。 ?使用该类是两个线程都调用了exchange(V v)方法才能交换。 ?如果只有一个线程调用了exchange(V v),程序会一直等待。 ?代码测试:一个线程调用exchanger(V v)方法时。
import java.util.concurrent.Exchanger;
public class Test {
public static void main(String[] args) {
Exchanger<Integer> change= new Exchanger<>();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("线程1");
try{
Thread.sleep(1000);
Integer t = 1;
t = change.exchange(t);
System.out.println( Thread.currentThread().getName()+" t = " +t);
}catch (Exception e){
}
}
}).start();
}
}
?他会一直等
?代码测试: 交换两个线程的Integer数据
import java.util.concurrent.Exchanger;
public class Test {
public static void main(String[] args) {
Exchanger<Integer> change= new Exchanger<>();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("线程1");
try{
Integer t = 1;
t = change.exchange(t);
System.out.println( Thread.currentThread().getName()+" t = " +t);
}catch (Exception e){
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("线程2");
try{
Integer t = 5;
t = change.exchange(t);
System.out.println( Thread.currentThread().getName() +" t = " +t);
}catch(Exception e){
}
}
}).start();
}
}
?运行结果: ?如果是多个线程进行数据交换,就是先来先交换。最终交换结果会不固定。 ?代码测试: 4个线程睡1秒之后都交换数据。
import java.util.concurrent.Exchanger;
public class Test {
public static void main(String[] args) {
Exchanger<Integer> change= new Exchanger<>();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("线程1");
try{
Thread.sleep(1000);
Integer t = 1;
t = change.exchange(t);
System.out.println( Thread.currentThread().getName()+" t = " +t);
}catch (Exception e){
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("线程2");
try{
Thread.sleep(1000);
Integer t = 2;
t = change.exchange(t);
System.out.println( Thread.currentThread().getName() +" t = " +t);
}catch(Exception e){
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("线程3");
try{
Thread.sleep(1000);
Integer t = 3;
t = change.exchange(t);
System.out.println( Thread.currentThread().getName() +" t = " +t);
}catch(Exception e){
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Thread.currentThread().setName("线程4");
try{
Thread.sleep(1000);
Integer t = 4;
t = change.exchange(t);
System.out.println( Thread.currentThread().getName() +" t = " +t);
}catch(Exception e){
}
}
}).start();
}
}
|