当我第二次运行线程时:java.lang.IllegalThreadStateException:线程已经启动
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23007381/
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
When I run Thread second time: java.lang.IllegalThreadStateException: Thread already started
提问by drozdzynski
I have Thrad and Handler:
我有 Thrad 和 Handler:
Handler handler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
//do somethink
}
};
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//do somethink
msg.obj = 1;
handler.sendMessage(msg);
thread.interrupt();
}
});
When app start, at first time thread.start();all work fine. But when I try start thread.start();second time from button I have:
当应用程序启动时,第一次thread.start(); 一切正常。但是当我尝试 start thread.start(); 第二次从按钮我有:
E/MessageQueue-JNI﹕ java.lang.IllegalThreadStateException: Thread already started.
E/MessageQueue-JNI: java.lang.IllegalThreadStateException: 线程已经启动。
采纳答案by The Holy Coder
You should check state of that thread before starting it.
您应该在启动之前检查该线程的状态。
if (thread.getState() == Thread.State.NEW)
{
thread.start();
}
回答by Yuvaraja
Its not a good Idea to start a Thread more then once. You have to check Whether a Thread is already started or not. if Thread not started yet
多次启动线程不是一个好主意。您必须检查线程是否已经启动。如果线程尚未启动
if(!thread.isAlive()){
thread.start();
}
The Better Idea is to Create new Threadinstance.
更好的主意是创建新的线程实例。
回答by Ted Bigham
At the end of run(), your thread dies. If you want to keep it alive, then add a blocking queue to the thread and make run() a big while loop that reads from the queue. Instead of calling start for each message, just add it to the queue instead.
在 run() 结束时,您的线程将终止。如果你想让它保持活动状态,那么向线程添加一个阻塞队列并使 run() 成为一个从队列中读取的大 while 循环。不要为每条消息调用 start,而是将其添加到队列中。
Of course, you still have to call start() once (when your program initializes).
当然,您仍然必须调用 start() 一次(当您的程序初始化时)。