Java中按键时暂停/取消暂停线程
我希望有人能帮我。我一直在寻找这个问题的答案,大约一周了,但没有结果 我目前有一个自定义线程类,它实现了Java中按键时暂停/取消暂停线程,java,multithreading,key-bindings,Java,Multithreading,Key Bindings,我希望有人能帮我。我一直在寻找这个问题的答案,大约一周了,但没有结果 我目前有一个自定义线程类,它实现了Runnable,我想在按键时暂停它。根据我的研究,我了解到最好的方法是使用wait()和notify(),由使用密钥绑定的密钥触发 我的问题是,我怎样才能让它工作?我似乎无法在设置密钥绑定时不出错,我无法理解如何实现wait()和notify()而不陷入死锁。下面是一个简单的快照,可以让您开始: class PausableThread extends Thread { pr
Runnable
,我想在按键时暂停它。根据我的研究,我了解到最好的方法是使用wait()
和notify()
,由使用密钥绑定的密钥触发
我的问题是,我怎样才能让它工作?我似乎无法在设置密钥绑定时不出错,我无法理解如何实现
wait()
和notify()
而不陷入死锁。下面是一个简单的快照,可以让您开始:
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);
}
}
因此,您可以在某个地方启动线程newpausablethread().start()代码>
然后在UI线程上的按钮/按键侦听器中调用
在OnPauseKeyPress listenermPausableThread.pauseAction()中代码>,
对于OnResumeKeyPress,您可以调用mPausableThread.resumeAction()代码>
要完全停止踏板,只需中断它:mPausableThread.interrupt()代码>
希望有帮助。等待和通知用于同步。在我看来,您似乎希望使用诸如Thread.suspend()、Thread.stop()和Thread.resume()之类的方法,但由于这些方法可能会导致锁出现问题,因此不推荐使用这些方法
解决方案是使用一个helper变量,线程将定期检查它是否应该运行,否则将产生(或休眠)
为什么不使用暂停、停止或恢复:
简单解决方案:
例如,您是否已经经历过?看起来是一样的。如果没有看到你的尝试,你不可能猜到你做错了什么。否则,您的问题只不过是要求某人重新编写已经存在的教程。请通过显示您的代码尝试和询问有关您可能被卡住的具体问题来改进您的问题。