【发布时间】:2021-03-11 09:43:32
【问题描述】:
我有以下课程:
public class PawnThread implements Runnable {
public void start() {
thread.start();
}
@Override
public void run() {
try {
while (... some finish condition ...) {
move();
synchronized (this) {
while (suspendFlag) {
wait();
}
}
}
} catch (InterruptedException e) {
System.err.println(pawn.toString() + ": thread interrupted :(");
}
}
void move() {
... some blocking actions
}
synchronized void suspend() {
suspendFlag = true;
}
synchronized void resume() {
suspendFlag = false;
notify();
}
}
现在我有了它的对象列表:
private final List<PawnThread> pawnThreadList;
我定义了一些辅助方法来暂停所有这些:
public void suspendAll() {
pawnThreadList.forEach(PawnThread::suspend);
}
现在suspend() 方法只是关于更改标志。要求是,当我离开 suspendAll() 方法时,所有线程实际上都应该暂停(它们不能处于 RUNNABLE 状态) - 现在不是这样,因为对于其中一些,可能需要一些时间在暂停之前真正完成他们的工作。
我将不胜感激此解决方案的正确设计。
问候
【问题讨论】:
标签: java multithreading wait notify suspend