【发布时间】:2025-01-11 04:35:02
【问题描述】:
如果我按下一个按钮,线程应该结束,这会将 isButtonPressed 设置为 true。 我的问题是,如果想通过单击按钮使用 thread.start(runnable) 启动线程,我会得到:IllegalThreadStateException: Thread already started(我认为线程在中断后终止因为循环结束了,但是好像我错了)。
Thread thread = new Thread(runnable);
thread.start(runnable);
可运行的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--;
}
}
}
};
感谢您的帮助!
【问题讨论】:
-
添加到 Andrew 的答案,使用执行器服务而不是重新启动一个新线程。看看这个问题:*.com/questions/36398144/…
标签: java android multithreading