run vs start
run()
If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns.
start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
如何优雅的停止一个线程?
- 使用 boolean volatile variable
- 使用Thread.Interrupt
Using Thread.interrupt() is a perfectly acceptable way of doing this. In fact, it’s probably preferrable to a flag as suggested above. The reason being that if you’re in an interruptable blocking call (like Thread.sleep or using java.nio Channel operations), you’ll actually be able to break out of those right away.
If you use a flag, you have to wait for the blocking operation to finish and then you can check your flag. In some cases you have to do this anyway, such as using standard InputStream/OutputStream which are not interruptable.
In that case, when a thread is interrupted, it will not interrupt the IO, however, you can easily do this routinely in your code (and you should do this at strategic points where you can safely stop and cleanup)
if (Thread.currentThread().isInterrupted()) {
// cleanup and stop execution
// for example a break in a loop
}
Like I said, the main advantage to Thread.interrupt() is that you can immediately break out of interruptable calls, which you can’t do with the flag approach.
本文介绍了两种优雅地停止线程的方法:使用布尔变量和Thread.interrupt()方法。使用Thread.interrupt()的优势在于能够立即从可中断的操作中退出,而使用标志位则需要等待操作完成才能检查标志。
9315

被折叠的 条评论
为什么被折叠?



