java 一个线程死了之后我可以再次启动它吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5398459/
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
Can I start a thread again after it has died?
提问by Matt
If I use start() on a Thread object and the run() method returns, is it possible to call start() again?
如果我在 Thread 对象上使用 start() 并且 run() 方法返回,是否可以再次调用 start() ?
eg,
例如,
MyThread myThread = new MyThread();
myThread.start();
// run method executes and returns in 2 seconds
// sleep for 5 seconds to make sure the thread has died
myThread.start();
I'm just wondering because my code is throwing IllegalThreadStateExceptions, so want to know if it's because you can't do the above.
我只是想知道是因为我的代码抛出了 IllegalThreadStateExceptions,所以想知道是不是因为您不能执行上述操作。
回答by dty
No, you can't. And the Javadoc for the Thread.start()
method tells you that!
不,你不能。该Thread.start()
方法的 Javadoc告诉您这一点!
回答by Thomas
From a comment:
来自评论:
Is there anything else I could do to re-start a thread?
我还能做些什么来重新启动线程?
You could use ThreadPoolExecutor
, which would allow you to pass in tasks and let the service assign a thread to a task. When the task is finished, the thread goes idle until it gets the next task.
您可以使用ThreadPoolExecutor
,这将允许您传入任务并让服务将线程分配给任务。任务完成后,线程将空闲,直到获得下一个任务。
So, you don't restart a thread, but you would redo/resume a task.
因此,您不会重新启动线程,而是会重做/恢复任务。
回答by Peter C
Nope.
不。
From the Javadoc for java.lang.Thread:
It is never legal to start a thread more than once.
多次启动一个线程是不合法的。
回答by Greg
From the javadoc:
从javadoc:
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
多次启动一个线程是不合法的。特别是,线程一旦完成执行就可能不会重新启动。
See the Thread.start()javadoc for more information.
有关更多信息,请参阅Thread.start()javadoc。
There are other ways to accomplish what you are trying to do. For example, you could use new Threads that continue the work that was done in the Thread that has finished execution. You may also want to investigate the java.util.concurrent package.
还有其他方法可以完成您正在尝试做的事情。例如,您可以使用新线程继续执行已完成的线程中完成的工作。您可能还想研究java.util.concurrent 包。
回答by TurtleToes
Perhaps there is a better way of doing this if you want the thread to stop and restart multiple times. I have a tile caching thread in C++ that does something similar; it pauses when it's finished, and unpaused when it's needed again. I am new to Java, but from what I can tell, you can use Object.wait() to pause, and Object.notify() to resume threads. Maybe you could check those out in the documentation and redesign your thread to pause and resume instead of exiting.
如果您希望线程多次停止和重新启动,也许有更好的方法来执行此操作。我在 C++ 中有一个 tile 缓存线程,它执行类似的操作;它在完成时暂停,并在再次需要时取消暂停。我是 Java 新手,但据我所知,您可以使用 Object.wait() 暂停,使用 Object.notify() 恢复线程。也许您可以在文档中查看这些内容并重新设计您的线程以暂停和恢复而不是退出。