java - 我需要在JAVA中使用中断方法的实际情况是什么?

标签 java multithreading

我需要在 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/

相关文章:

java - 忽略 MongoRepository 中 getBy****() 函数中的参数

java - 存储在字符串池中的字符串文字是否唯一?

java - 无法在 java 中访问 getJSONArray

javascript - 共享数据问题

c++ - 一个线程结束后调用另一个线程中的方法

java - 从 jlink 图像创建所有包含 windows 可执行文件

java - MongoOperations 保存功能无法正常工作

android - Cordova /Phonegap : run FileTransfer plugin in background thread

c++ - 线程 : How to calculate precisely the execution time of an algorithm (duration of function) in C or C++?

java - CompletableFuture 与 Spring 事务