停止并重新启动已经运行的线程 [英] Stop and restart a already running thread
问题描述
如果我按下一个按钮,线程应该结束,这会将 isButtonPressed 设置为 true.我的问题是,如果想通过单击按钮使用 thread.start(runnable) 启动线程,我会得到以下信息:IllegalThreadStateException: Thread already start (我认为线程在中断后终止了因为循环结束了,但好像我错了).
The Thread should end if I press a button, which sets the isButtonPressed to true. My problem is, that if a want to start the thread with thread.start(runnable) by clicking the button, I get this: IllegalThreadStateException: Thread already started (I thought the thread was terminated after the break because the the loop is over, but it seems that I am wrong).
Thread thread = new Thread(runnable);
thread.start(runnable);
可运行的可运行:
Runnable runnable = new Runnable() {
@Override
public void run() {
time = 10;
for (int i = 10; i <= 10; i--) {
handler.post(new Runnable() {
@Override
public void run() {
txt_Time.setText(String.valueOf(time));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
if (isButtonPressed) {
break;
}
if (time == 0) {
resetVisibleState();
break;
} else {
time--;
}
}
}
};
感谢您的帮助!
推荐答案
Java 线程不可重新启动.对于您想要实现的目标,您可以每次创建一个新线程,或者您可以查看 ExecutorService.只需创建一个单线程执行程序 (Executors.newSingleThreadExecutor),并在每次需要运行时将可运行对象提交给它.
Java threads are not restartable. For what you are trying to achieve, you could create a new thread each time, or you could look at an ExecutorService. Just create a single threaded executor (Executors.newSingleThreadExecutor), and submit your runnable to it every time you need it to run.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(runnable);
这篇关于停止并重新启动已经运行的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!