线程死掉后我可以再次启动它吗?
如果我在 Thread 对象上使用 start() 并且 run() 方法返回,是否可以再次调用 start() ?
例如,
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();
我只是想知道因为我的代码抛出 IllegalThreadStateExceptions,所以想知道是否是因为您无法执行上述操作。
If I use start() on a Thread object and the run() method returns, is it possible to call start() again?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,你不能。以及
Thread.start()
方法告诉你这一点!No, you can't. And the Javadoc for the
Thread.start()
method tells you that!来自评论:
您可以使用 ThreadPoolExecutor,它允许您传入任务并让服务将线程分配给任务。当任务完成后,线程将处于空闲状态,直到获得下一个任务。
因此,您不会重新启动线程,但会重做/恢复任务。
From a comment:
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.So, you don't restart a thread, but you would redo/resume a task.
没有。
来自 java.lang 的 Javadoc .线程:
Nope.
From the Javadoc for java.lang.Thread:
来自javadoc:
请参阅 Thread.start () javadoc 了解更多信息。
还有其他方法可以完成您想要做的事情。例如,您可以使用新线程来继续已完成执行的线程中完成的工作。您可能还想调查 java.util.concurrent 包。
From the javadoc:
See the Thread.start() javadoc for more information.
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.
如果您希望线程多次停止并重新启动,也许有更好的方法来执行此操作。我在 C++ 中有一个瓦片缓存线程,可以执行类似的操作;它在完成时暂停,并在再次需要时取消暂停。我是 Java 新手,但据我所知,您可以使用 Object.wait() 暂停,并使用 Object.notify() 恢复线程。也许您可以在文档中查看这些内容并重新设计线程以暂停和恢复而不是退出。
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.