如何暂停然后恢复一个线程?

新手上路,请多包涵

我声明我读过有关线程的信息,但我从未使用过。所以我问你:)

I have two thread: A and B , where A manages the GUI, and B manages the logic.

我将从 A 开始。

然后当 A 绘制 GUI 时,我会暂停它,等待 B 到达点 X 进入运行方法。

B 到达运行方法的 X 点时,我暂停 B ,然后恢复 A

AB 共享一些变量来管理GUI和逻辑……

我可以做吗?如果是,如何? :)

原文由 Teo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 456
2 个回答

使用 wait()notify() 方法:

wait() - 导致当前线程等待,直到另一个线程为此对象调用 notify() 方法或 notifyAll() 方法。

notify() - 唤醒在此对象的监视器上等待的单个线程。

原文由 Dineshkumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 Object 类的 waitnotify 方法来阻止线程,但要做到正确可能会很棘手。这是 Runnable 中无限循环内的示例:

 public class Example implements Runnable {
    private volatile boolean running = true;
    private volatile boolean paused = false;
    private final Object pauseLock = new Object();

    @Override
    public void run() {
        while (running) {
            synchronized (pauseLock) {
                if (!running) { // may have changed while waiting to
                    // synchronize on pauseLock
                    break;
                }
                if (paused) {
                    try {
                        pauseLock.wait(); // will cause this Thread to block until
                        // another thread calls pauseLock.notifyAll()
                        // Note that calling wait() will
                        // relinquish the synchronized lock that this
                        // thread holds on pauseLock so another thread
                        // can acquire the lock to call notifyAll()
                        // (link with explanation below this code)
                    } catch (InterruptedException ex) {
                        break;
                    }
                    if (!running) { // running might have changed since we paused
                        break;
                    }
                }
            }
            // Your code here
        }
    }

    public void stop() {
        running = false;
        // you might also want to interrupt() the Thread that is
        // running this Runnable, too, or perhaps call:
        resume();
        // to unblock
    }

    public void pause() {
        // you may want to throw an IllegalStateException if !running
        paused = true;
    }

    public void resume() {
        synchronized (pauseLock) {
            paused = false;
            pauseLock.notifyAll(); // Unblocks thread
        }
    }
};

(有关为什么我们需要在调用 waitnotifyAll 时进行同步的更多信息,请参阅 有关该主题的 Java 教程。)

如果另一个 Thread 调用了这个 Runnable 的 pause() 方法,那么运行这个 runnable 的 Thread 在到达 while 循环的顶部时就会阻塞。

请注意,不可能在任意点暂停线程。您需要线程定期检查它是否应该暂停并在暂停时阻塞自己。

原文由 daiscog 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题