我希望有人可以帮助我。我一直在寻找一个星期的答案来解决这个问题,但没有用。
我目前有一个实现Runnable
的自定义线程类,我想在按键时暂停。根据我的研究,我了解到最好的方法是使用wait()
和notify()
,由使用键绑定的键触发。
我的问题是,我怎样才能让它发挥作用?我似乎无法在没有出错的情况下设置密钥绑定,以及如何在不遇到死锁的情况下实现wait()
和notify()
是超出我的。
答案 0 :(得分:1)
等待和通知意味着用于同步。在我看来,你想使用像Thread.suspend(),Thread.stop()和Thread.resume()这样的方法,但是这些方法已经被弃用,因为它们会导致锁定问题的风险。
解决方案是使用一个辅助变量,线程会定期检查它是否应该运行,否则,yield(或sleep)
为什么不使用暂停,停止或恢复:http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
简单的解决方案: How to Pause and Resume a Thread in Java from another Thread
答案 1 :(得分:0)
这是一个可以帮助您入门的简单快照:
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();
,
对于OnResumeKeyPress,您可以拨打mPausableThread.resumeAction();
要完全停止行动,只需打断它:mPausableThread.interrupt();
希望有所帮助。