我有以下类(class):
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
状态)-现在不是这种情况了,因为其中某些线程可能需要一些时间才能真正完成其工作。停顿之前。我将不胜感激,为该解决方案提供正确的设计建议。
问候
最佳答案
使PawnThread#suspend()
等待完成挂起:
public class PawnThread implements Runnable {
private final Waiter suspender = new Waiter();
private final Waiter suspending = new Waiter();
@Override
public void run() {
try {
while (...) {
suspending.suspend();
move();
suspending.resume();
suspender.await();
}
} catch (InterruptedException e) {
...
}
}
void suspend() throws InterruptedException {
suspender.suspend();
suspending.await();
}
void resume() {
suspender.resume();
}
}
public class Waiter {
private boolean waiting;
public synchronized void await() throws InterruptedException {
while (waiting) {
wait();
}
}
public synchronized void suspend() {
waiting = true;
}
public synchronized void resume() {
waiting = false;
notify();
}
}
关于java - 确保Java线程确实被挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65057138/