Thread

本文介绍了两种优雅地停止线程的方法:使用布尔变量和Thread.interrupt()方法。使用Thread.interrupt()的优势在于能够立即从可中断的操作中退出,而使用标志位则需要等待操作完成才能检查标志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

如何优雅的停止一个线程?

  1. 使用 boolean volatile variable
  2. 使用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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值