如何从按钮重新启动 java/Android 中的线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3826402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I restart a thread in java/Android from a button?
提问by Martin
I have a thread in java/Android like this:
我在 java/Android 中有一个像这样的线程:
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
update_i();
}
};
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Thread myThread = new Thread(new Runnable() {
public void run() {
while (true) {
try {
handler.sendMessage(handler.obtainMessage());
Thread.sleep(timer);
} catch (Throwable t) {
}
}
}
});
myThread.start();
}
The thread works fine when I run my application. But I want to start/restart the thread with a button.
当我运行我的应用程序时,线程工作正常。但我想用按钮启动/重新启动线程。
Button.OnClickListener StartButtonOnClickListener = new Button.OnClickListener() {
@Override
public void onClick(View v) {
//start/restart the thread
}
};
If I copy the thread into the button I just make a new thread every time the user clicks on the button. I want to run the thread when the user first time click on the button, "kill it" and start from the beginning if the user click on the button a second time (I don't want to start a second thread).
如果我将线程复制到按钮中,则每次用户单击按钮时我都会创建一个新线程。我想在用户第一次单击按钮时运行线程,如果用户第二次单击按钮,则“杀死它”并从头开始(我不想启动第二个线程)。
回答by mklfarha
I think that Colin is wright you can′t just restart you need to make a new instance, and the interrupt function will stop the running thread if it is still running.
我觉得 Colin 很聪明,你不能只是重启你需要创建一个新的实例,如果它仍在运行,中断函数会停止正在运行的线程。
I recommend you make an inner class, instand of an inline implementation, it will make it easier to understand.
我建议你创建一个内部类,代替内联实现,它会更容易理解。
if(myThread.isAlive()){
myThread.interrupt();
}
myThread = new MyThread();
myThread.start();
hope this helps
希望这可以帮助
回答by Colin Hebert
You can't restart a Thread.
您无法重新启动线程。
From the documentation :
从文档:
Throws IllegalThreadStateException
if the Thread has been started before
You can kill the previous thread, but in the end you will have to create a second instance of your thread.
您可以终止前一个线程,但最终您必须创建线程的第二个实例。
Resources :
资源 :