我有一段代码,我想使用wait()和notify()来确保机器人腿的移动顺序。代码如下:
public class Leg implements Runnable {
private final Object monitor = new Object();
private final String name;
public Leg(String name) {
this.name = name;
}
@Override
public void run() {
while (true) {
synchronized (monitor) {
move();
monitor.notify();
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void move() {
System.out.println(name);
}
public static void main(String[] args) {
CompletableFuture.allOf(
CompletableFuture.runAsync(new Leg("left")),
CompletableFuture.runAsync(new Leg("right"))
).join();
}
}现在的输出如下:
left
right
// and then it stops moving.我希望代码继续移动(不只移动一次)。这就是为什么我感兴趣的原因是我做错了什么?
发布于 2021-03-30 17:31:01
你有两个Leg对象和两个线程要处理,每个线程都有一个monitor对象,所以当你使用notify和wait时,它只影响一个线程(当前正在运行的线程):
synchronized (monitor) {
move();
monitor.notify(); // notify current thread, it's no meaning
try {
monitor.wait(); // current thread will block here and there is no thread wake up it
} catch (InterruptedException e) {
e.printStackTrace();
}
}也许这就是你需要的:
import java.util.concurrent.CompletableFuture;
public class Leg implements Runnable {
private final String name;
private Leg nextLeg;
private volatile boolean active;
public Leg(String name) {
this.name = name;
}
public void setNextLeg(Leg nextLeg) {
this.nextLeg = nextLeg;
}
public void active() {
synchronized (this) {
this.active = true;
notify();
}
}
@Override
public void run() {
while (true) {
try {
synchronized (this) {
while (!active) {
wait();
}
move();
active = false;
nextLeg.active();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
private void move() {
System.out.println(name);
}
public static void main(String[] args) {
Leg left = new Leg("left");
Leg right = new Leg("right");
left.setNextLeg(right);
right.setNextLeg(left);
left.active();
CompletableFuture.allOf(
CompletableFuture.runAsync(left),
CompletableFuture.runAsync(right)
).join();
}
}https://stackoverflow.com/questions/66861236
复制相似问题