我有以下代码。代码分别创建两个带有消息“Hello”和“World”的runnable。 我希望这与“世界”交换“你好”,但它不起作用。代码卡住了,交换永远不会发生
更改代码如下。它现在有效
public class ExchangerExample {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger();
new Thread(() -> {
try {
String message = "Hello";
Object previous = message;
message = exchanger.exchange(message);
System.out.println(previous + " is changed to " + message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
try {
String message = "World";
Object previous = message;
message = exchanger.exchange(message);
System.out.println(previous + " is changed to " + message);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
答案 0 :(得分:0)
首先这不是编写这样的程序的好设计,看起来像spagetti代码,先写一个ExchangerRunnable
类:
public class ExchangerRunnable implements Runnable{
Exchanger exchanger = null;
Object object = null;
public ExchangerRunnable(Exchanger exchanger, Object object) {
this.exchanger = exchanger;
this.object = object;
}
public void run() {
try {
Object previous = this.object;
this.object = this.exchanger.exchange(this.object);
System.out.println(
Thread.currentThread().getName() +
" exchanged " + previous + " for " + this.object
);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
然后您可以按照以下方式使用它:
Exchanger exchanger = new Exchanger();
ExchangerRunnable exchangerRunnable1 =
new ExchangerRunnable(exchanger, "Hello");
ExchangerRunnable exchangerRunnable2 =
new ExchangerRunnable(exchanger, "World");
new Thread(exchangerRunnable1).start();
new Thread(exchangerRunnable2).start();
输出将是:
Thread-0 exchanged Hello for World
Thread-1 exchanged World for Hello
有什么问题吗?