java - 确保Java线程确实被挂起

标签 java multithreading wait notify suspend

我有以下类(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/

相关文章:

java - Java 中一个线程可以同时调用两个锁的 wait() (6)

java - 为什么 JMS MessageListener 中使用的实体管理器不参与 JTA 事务?

java - Http 请求无响应 : Apache Tomcat

multithreading - HTTP GET 多线程脚本

ios - 无法取消 OperationQueue swift 中的执行操作

Python:如何避免线程中的 'wait'停止程序流?

java - 使用 PrintWriter 将字符串写入日志文件

java - Android - 每单位时间执行操作

java - 如何使用 ExecutorService 递归调度任务

javascript - 如何在 JavaScript 中将整个脚本暂停一段时间?这可能吗?