java中断的确切用法是什么?

时间:2012-09-11 20:57:02

标签: java concurrency interrupt

我是Java concurrecny的新手,我现在正在阅读这篇文章:Java Tutorial-Interrupts但我无法真正理解我应该使用中断的地点和原因。有人可以给我一个例子(代码),所以我更好地理解它? THX

3 个答案:

答案 0 :(得分:3)

当您想要(咳嗽)中断线程时使用中断 - 通常意味着停止操作。由于各种问题,Thread.stop()已被弃用,因此Thread.interrupt()是告诉线程它应该停止运行的方式 - 它应该清理它正在做什么并退出。实际上,程序员可以以任何他们想要的方式在线程上使用中断信号。

一些例子:

  • 你的线程可能正在睡眠一分钟,然后抓住一个网页。你希望它能阻止这种行为。
  • 也许你有一个正在从一系列工作中消耗的线程,而你想告诉它没有更多的工作正在进行中。
  • 也许你有许多你想要中断的后台线程,因为这个过程正在关闭,你想要干净利落。

有很多方法可以实现上述信令,但可以使用中断。

Thread.interrupt()影响正在运行的主题的一种更强大的方法是从InterruptedExceptionThread.sleep()等其他方法中抛出Object.wait()

try {
   Thread.sleep(1000);
} catch (InterruptedException e) {
   // i've been interrupted
   // catching InterruptedException clears the interrupt status on the thread
   // so a good pattern is to re-interrupt the thread
   Thread.currentThread().interrupt();
   // but maybe we want to just kill the thread
   return;
}

此外,通常在一个线程中我们循环执行某项任务,因此我们检查中断状态:

while (!Thread.currentThread().isInterrupted()) {
    // keep doing our task until we are interrupted
}

答案 1 :(得分:1)

使用多线程,我们的想法是你有一些工作可以在几个线程之间划分。经典的例子是拥有一个执行后台计算的线程或一个后台操作,例如服务器查询,这将花费相当多的时间而不在​​处理用户界面的主线程中执行该操作。

通过卸载可能需要花费大量时间的操作,可以防止用户界面看起来卡住。例如,当您在显示的对话框中启动操作时,转到另一个窗口然后返回到显示的对话框,当您单击它时对话框不会自动更新。

有时需要停止后台活动。在这种情况下,您将使用Thread.interrupt()方法请求线程停止自己。

示例可能是您的客户端每秒从服务器获取一次状态信息。后台线程处理与服务器的通信并获取数据。用户界面线程获取数据并更新显示。然后用户按下显示屏上的停止或取消按钮。然后,用户界面线程在后台线程上执行中断,以便它将停止从服务器请求状态信息。

答案 2 :(得分:0)

在并发编程中,许多程序员得出的结论是他们需要停止一个线程。他们决定让某种boolean标志告诉线程它应该停止是个好主意。中断标志是通过Java标准库提供的布尔机制。

例如:

class LongIterativeTask implements Runnable {
    public void run() {
        while (!thread.isInterrupted()) { //while not interrupted
            //do an iteration of a long task
        }
    }
 }

class LongSequentialTask implements Runnable {
    public void run() {
        //do some work
        if (!thread.isInterrupted()) { //check flag before starting long process
            //do a lot of long work that needs to be done in one pass
        }
        // do some stuff to setup for next step
        if (!thread.isInterrupted()) { //check flag before starting long process
            //do the next step of long work that needs to be done in one pass
        }
    }
 }
相关问题