在 Java 中按键时暂停/取消暂停线程



我希望有人能帮我解决这个问题。我一直在寻找大约一周的答案,但无济于事。

我目前有一个实现Runnable的自定义线程类,我想在按键时暂停。根据我的研究,我了解到最好的方法是使用 wait()notify() ,由使用键绑定的键触发。

我的问题是,我怎样才能让它工作?我似乎无法在不出错的情况下设置密钥绑定,而如何在不遇到僵局的情况下实现wait()notify()超出了我的范围。

等待和通知用于同步。在我看来,你想使用像Thread.suspend(),Thread.stop()和Thread.resume()这样的方法,但是由于它们导致锁定问题的风险,这些方法已被弃用。

解决方案是使用一个辅助变量,线程将定期检查它是否应该运行,否则,yield(或睡眠)

为什么不使用暂停、停止或恢复:http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

简单的解决方案:如何在 Java 中从另一个线程暂停和恢复线程

http://www.tutorialspoint.com/java/java_thread_control.htm

这是一个简单的快照,可能会让你开始:

class PausableThread extends Thread {
        private volatile boolean isPaused;
        @Override
        public void run() {
            while (true /* or some other termination condition */) {
                try {
                    waitUntilResumed();
                    doSomePeriodicAction();
                } catch (InterruptedException e) {
                    // we've been interrupted. Stop
                    System.out.println("interrupted. Stop the work");
                    break;
                }
            }
        }
        public void pauseAction() {
            System.out.println("paused");
            isPaused = true;
        }
        public synchronized void resumeAction() {
            System.out.println("resumed");
           isPaused = false; 
           notifyAll();
        }
        // blocks current thread until it is resumed
        private synchronized void waitUntilResumed() throws InterruptedException {
            while (isPaused) {
                wait();
            }
        }
        private void doSomePeriodicAction() throws InterruptedException {
            System.out.println("doing something");
            thread.sleep(1000);
        }
    }

因此,您在某个地方开始您的线程new PausableThread().start();

然后在您调用
的 UI 线程上的按钮/按键侦听器在 OnPauseKeyPress 侦听器mPausableThread.pauseAction(); 中,
对于恢复按键,您可以拨打mPausableThread.resumeAction();

要完全停止踩踏,只需打断它:mPausableThread.interrupt();

希望有帮助。

最新更新