gpt4 book ai didi

java - NotifyAll 无法正常工作 : program to control thread execution order - print integers sequentially

转载 作者:行者123 更新时间:2023-12-02 03:46:44 25 4
gpt4 key购买 nike

首先,这不是作业。我写了一段代码:

Thread-1 打印 1,4,7,...(差异为 3)

Thread-2 打印 2,5,8,...

Thread-3 打印 3,6,9,...

最终输出应该是:

1,2,3,4,5,6,7,8,9,...

下面的代码运行得非常好:

package threadAlgo;

public class ControlOrder {
volatile Monitor monitor = new Monitor();

public static void main(String[] args) {
ControlOrder order = new ControlOrder();

Thread one = new Thread(new Task(order.monitor, 1));
one.setName("Thread-1");
Thread two = new Thread(new Task(order.monitor, 2));
two.setName("Thread-2");
Thread three = new Thread(new Task(order.monitor, 3));
three.setName("Thread-3");

one.start();
two.start();
three.start();
}
}

class Monitor {
int threadNumber = 1;
}

class Task implements Runnable {

private Monitor monitor;
private int myThreadNumber;
private int currentCount;

Task(Monitor monitor, int myThreadNumber) {
this.monitor = monitor;
this.myThreadNumber = myThreadNumber;
this.currentCount = myThreadNumber;
}

@Override
public void run() {
while (true) {
while (monitor.threadNumber != myThreadNumber) {
synchronized (monitor) {
try {
monitor.wait(100); //DOESN'T WORK WITHOUT THE TIMEOUT!!!
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

synchronized (monitor) {
if (monitor.threadNumber == myThreadNumber) {
System.out.println(Thread.currentThread().getName() + ": " + currentCount);
currentCount = currentCount + 3;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (myThreadNumber == 3) {
monitor.threadNumber = 1;
} else {
monitor.threadNumber = myThreadNumber + 1;
}
monitor.notifyAll();
}

}
}
}

唯一的问题是,如果我使用 wait() 而不是 wait(timeout),那么线程将停止。

更新:

等待条件(while 循环)应该位于同步块(synchronized block)内。这是给包括我在内的初学者的一课。

最佳答案

你应该始终

  • 结合状态更改执行notifyAll/notify。
  • 在循环中使用 wait() 之前检查状态更改。

如果您调用notify()并且没有wait()在等待,那么信号就会丢失,因此除非您检查状态更改(或超时),否则您可以永远阻塞等待不更改的信号。

关于java - NotifyAll 无法正常工作 : program to control thread execution order - print integers sequentially,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36222251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com