我需要在 JAVA 中使用中断方法的实际情况是什么?
最佳答案
有一些示例,大多数都涉及关闭线程的意图。如果您想中断线程( documentation of Thread#interrupt ),则需要它。
<小时/>一个例子可能是发生异常,即常规执行发生异常。您希望线程立即监听并处理新情况。
或者如果您想关闭线程。然后,您可以使用中断来确保线程对您的关闭调用使用react,并且不会继续 hibernate 几秒钟左右。
或者想象一个应用程序安装一个程序大约需要 10 分钟。您可能需要一个取消按钮来中止安装过程。然后,分配给该按钮的方法可以在后台使用中断
来确保进程及时取消。
如果我们将其分解,那么它只是一个可以设置和检查的常规标志。您可以使用Thread#interrupt
设置它,并通过Thread#isInterrupted
检查它。
Java 库中有多种方法已经使用此标志,例如 Thread#sleep ,如果在 sleep 时设置该标志,则会抛出 InterruptedException
。
这是一个小型展示示例:
public class Waiter extends Thread {
private volatile boolean mShouldStop = false;
@Override
public void run() {
while (!this.mShouldStop) {
System.out.println("Still there!");
try {
// Sleep for 10 seconds
Thread.sleep(10_000);
} catch (final InterruptedException e) {
// Abort sleeping, got interrupted.
}
}
System.out.println("Shutting down!");
}
public void shutdown() {
this.mShouldStop = true;
}
}
以及用法:
public class Demo {
public static void main(final String[] args) throws InterruptedException {
// Create and start the thread
final Waiter waiter = new Waiter();
System.out.println("Start");
waiter.start();
// Wait some seconds
Thread.sleep(25_000);
// Stop the thread, use interrupt to wake it up in case it slept
System.out.println("Kindly ask for shutdown");
waiter.shutdown();
System.out.println("Interrupt it");
waiter.interrupt();
}
}
如果没有中断,线程只会在完成 hibernate 后对关闭调用使用react,因此还需要 5 秒。
请注意:volatile
关键字可确保在线程更改对象后,所有线程都将获取更新后的变体,而不适用于旧的缓存变体。
关于java - 我需要在JAVA中使用中断方法的实际情况是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45895981/