java.lang.Thread.interrupt() 有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3590000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:16:04  来源:igfitidea点击:

What does java.lang.Thread.interrupt() do?

javamultithreading

提问by oneat

Could you explain what java.lang.Thread.interrupt()does when invoked?

你能解释一下java.lang.Thread.interrupt()被调用时的作用吗?

采纳答案by Mike Q

Thread.interrupt()sets the interrupted status/flag of the target thread. Then code running in that target thread MAY poll the interrupted status and handle it appropriately. Some methods that block such as Object.wait()may consume the interrupted status immediately and throw an appropriate exception (usually InterruptedException)

Thread.interrupt()设置目标线程的中断状态/标志。然后在该目标线程中运行的代码可能会轮询中断状态并对其进行适当处理。一些阻塞的方法例如Object.wait()可能会立即消耗中断状态并抛出适当的异常(通常InterruptedException

Interruption in Java is not pre-emptive. Put another way both threads have to cooperate in order to process the interrupt properly. If the target thread does not poll the interrupted status the interrupt is effectively ignored.

Java 中的中断不是先发制人的。换句话说,两个线程必须合作才能正确处理中断。如果目标线程不轮询中断状态,则中断将被有效地忽略。

Polling occurs via the Thread.interrupted()method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.

轮询通过Thread.interrupted()返回当前线程的中断状态并清除该中断标志的方法进行。通常线程随后可能会执行诸如抛出 InterruptedException 之类的操作。

EDIT (from Thilo comments): Some API methods have built in interrupt handling. Of the top of my head this includes.

编辑(来自 Thilo 评论):一些 API 方法内置了中断处理。在我的头顶,这包括。

  • Object.wait(), Thread.sleep(), and Thread.join()
  • Most java.util.concurrentstructures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.
  • Object.wait(), Thread.sleep(), 和Thread.join()
  • 大多数java.util.concurrent结构
  • Java NIO(但不是 java.io)并且它不使用InterruptedException,而是使用ClosedByInterruptException.

EDIT (from @thomas-pornin's answer to exactly same questionfor completeness)

编辑(来自@thomas-pornin完全相同问题的完整回答)

Thread interruption is a gentle way to nudge a thread. It is used to give threads a chance to exit cleanly, as opposed to Thread.stop()that is more like shooting the thread with an assault rifle.

线程中断是一种轻推线程的温和方式。它用于让线程有机会干净地退出,而Thread.stop()这更像是用突击步枪射击线程。

回答by Thilo

If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.

如果目标线程一直在等待(通过调用wait(),或其他一些本质上执行相同操作的相关方法,例如sleep()),它将被中断,这意味着它停止等待它正在等待的内容,而是接收一个 InterruptedException。

It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.

wait()在这种情况下,完全由线程本身(调用 的代码)来决定要做什么。它不会自动终止线程。

It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.

它有时与终止标志结合使用。当被中断时,线程可以检查这个标志,然后关闭自己。但同样,这只是一个约定。

回答by YoK

What is interrupt ?

什么是中断?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

中断是对线程的指示,它应该停止正在执行的操作并执行其他操作。由程序员决定线程如何响应中断,但线程终止是很常见的。

How is it implemented ?

它是如何实施的?

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static Thread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

中断机制是使用称为中断状态的内部标志实现的。调用 Thread.interrupt 设置此标志。当线程通过调用静态方法 Thread.interrupted 检查中断时,中断状态被清除。一个线程使用非静态 Thread.isInterrupted 来查询另一个线程的中断状态,它不会更改中断状态标志。

Quote from Thread.interrupt()API:

来自Thread.interrupt()API 的报价:

Interrupts this thread. First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

If none of the previous conditions hold then this thread's interrupt status will be set.

中断此线程。首先调用该线程的checkAccess方法,可能会导致抛出SecurityException。

如果此线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法或 join()、join(long)、join(long, int) 方法时被阻塞、sleep(long) 或 sleep(long, int) 等方法,那么它的中断状态将被清除,并且它会收到一个 InterruptedException。

如果此线程在可中断通道上的 I/O 操作中被阻塞,则通道将关闭,线程的中断状态将被设置,线程将收到 ClosedByInterruptException。

如果此线程在 Selector 中被阻塞,则该线程的中断状态将被设置,并且它将立即从选择操作中返回,可能具有非零值,就像调用了选择器的唤醒方法一样。

如果前面的条件都不成立,则将设置此线程的中断状态。

Check this out for complete understanding about same :

检查这个以完全理解相同的内容:

http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

http://download.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

回答by Evgeni Sergeev

For completeness, in addition to the other answers, if the thread is interrupted before it blocks on Object.wait(..)or Thread.sleep(..)etc., this is equivalent to it being interrupted immediately upon blocking on that method, as the following example shows.

为了完整起见,除了其他的答案,如果线程被中断就可以了块之前Object.wait(..)Thread.sleep(..)等等,这是相当于它在阻塞该方法被立即中断,如以下示例所示。

public class InterruptTest {
    public static void main(String[] args) {

        Thread.currentThread().interrupt();

        printInterrupted(1);

        Object o = new Object();
        try {
            synchronized (o) {
                printInterrupted(2);
                System.out.printf("A Time %d\n", System.currentTimeMillis());
                o.wait(100);
                System.out.printf("B Time %d\n", System.currentTimeMillis());
            }
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("C Time %d\n", System.currentTimeMillis());

        printInterrupted(3);

        Thread.currentThread().interrupt();

        printInterrupted(4);

        try {
            System.out.printf("D Time %d\n", System.currentTimeMillis());
            Thread.sleep(100);
            System.out.printf("E Time %d\n", System.currentTimeMillis());
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("F Time %d\n", System.currentTimeMillis());

        printInterrupted(5);

        try {
            System.out.printf("G Time %d\n", System.currentTimeMillis());
            Thread.sleep(100);
            System.out.printf("H Time %d\n", System.currentTimeMillis());
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("I Time %d\n", System.currentTimeMillis());

    }
    static void printInterrupted(int n) {
        System.out.printf("(%d) Am I interrupted? %s\n", n,
                Thread.currentThread().isInterrupted() ? "Yes" : "No");
    }
}

Output:

输出:

$ javac InterruptTest.java 

$ java -classpath "." InterruptTest
(1) Am I interrupted? Yes
(2) Am I interrupted? Yes
A Time 1399207408543
WAS interrupted
C Time 1399207408543
(3) Am I interrupted? No
(4) Am I interrupted? Yes
D Time 1399207408544
WAS interrupted
F Time 1399207408544
(5) Am I interrupted? No
G Time 1399207408545
H Time 1399207408668
I Time 1399207408669

Implication: if you loop like the following, and the interrupt occurs at the exact moment when control has left Thread.sleep(..)and is going around the loop, the exception is still going to occur. So it is perfectly safe to rely on the InterruptedException being reliably thrown after the thread has been interrupted:

含义:如果你像下面这样循环,并且中断发生在控制权离开Thread.sleep(..)并绕过循环的确切时刻,异常仍然会发生。因此,依靠在线程中断后可靠地抛出 InterruptedException 是完全安全的

while (true) {
    try {
        Thread.sleep(10);
    } catch (InterruptedException ie) {
        break;
    }
}

回答by Ajeet Ganga

public void interrupt()

公共无效中断()

Interrupts this thread.

中断此线程。

Unless the current thread is interrupting itself, which is always permitted, the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.

除非当前线程自己中断,这总是被允许的,否则调用此线程的 checkAccess 方法,这可能会导致抛出 SecurityException。

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

如果此线程在调用 Object 类的 wait()、wait(long) 或 wait(long, int) 方法或 join()、join(long)、join(long, int) 方法时被阻塞、sleep(long) 或 sleep(long, int) 等方法,那么它的中断状态将被清除,并且它会收到一个 InterruptedException。

If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.

如果此线程在可中断通道上的 I/O 操作中被阻塞,则通道将关闭,线程的中断状态将被设置,线程将收到 ClosedByInterruptException。

If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.

如果此线程在 Selector 中被阻塞,则该线程的中断状态将被设置,并且它将立即从选择操作中返回,可能具有非零值,就像调用了选择器的唤醒方法一样。

If none of the previous conditions hold then this thread's interrupt status will be set.

如果前面的条件都不成立,则将设置此线程的中断状态。

Interrupting a thread that is not alive need not have any effect.

中断一个不活跃的线程不需要有任何影响。

Throws: SecurityException - if the current thread cannot modify this thread

抛出: SecurityException - 如果当前线程不能修改这个线程

回答by Adi

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. A very good referance: https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

中断是对线程的指示,它应该停止正在执行的操作并执行其他操作。由程序员决定线程如何响应中断,但线程终止是很常见的。一个很好的参考:https: //docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

回答by Sanchi Girotra

Thread.interrupt()sets the interrupted status/flag of the target thread to true which when checked using Thread.interrupted()can help in stopping the endless thread. Refer http://www.yegor256.com/2015/10/20/interrupted-exception.html

Thread.interrupt()将目标线程的中断状态/标志设置为 true,在检查使用时Thread.interrupted()可以帮助停止无限线程。参考http://www.yegor256.com/2015/10/20/interrupted-exception.html

回答by akash G

Thread interruption is based on flag interrupt status. For every thread default value of interrupt statusis set to false. Whenever interrupt()method is called on thread, interrupt status is set to true.

线程中断基于标志中断状态。对于每个线程,中断状态的默认值设置为false。每当在线程上调用interrupt()方法时,中断状态都会设置为true

  1. If interrupt status = true (interrupt() already called on thread), that particular thread cannotgo to sleep. If sleep is called on that thread interrupted exception is thrown. After throwing exception again flag is set to false.
  2. If thread is already sleeping and interrupt()is called, thread will come out of sleeping state and throw interrupted Exception.
  1. 如果中断状态 = true(interrupt() 已在线程上调用),则该特定线程无法进入睡眠状态。如果在该线程上调用 sleep 会引发中断异常。再次抛出异常后,标志设置为 false。
  2. 如果线程已经在休眠并且调用了interrupt(),则线程将退出休眠状态并抛出中断的异常。

回答by Anatoliy Shuba

Thread.interrupt() method sets internal 'interrupt status' flag. Usually that flag is checked by Thread.interrupted() method.

Thread.interrupt() 方法设置内部“中断状态”标志。通常该标志由 Thread.interrupted() 方法检查。

By convention,any method that exists via InterruptedException have to clear interrupt status flag.

按照惯例,任何通过 InterruptedException 存在的方法都必须清除中断状态标志。