Java: Различие в использовании между Thread.interrupted () и Thread.isInterrupted ()?

Вопрос о Java: Насколько я знаю, существует два способа проверить в потоке, получил ли поток сигнал прерывания, Thread.interrupted() и Thread.isInterrupted(), и единственная разница между ними то, что бывший сброс внутренний прерванный флаг.

До сих пор я всегда использовал Thread.isInterrupted() и никогда не имел проблем с ним. С другой стороны большинство учебных руководств, которые я видел, рекомендует использовать Thread.interrupted(). Есть ли какая-либо определенная причина этого?

54
задан sahli mohamed mehdi M sahli 23 May 2018 в 01:15
поделиться

6 ответов

interrupted() is static and checks the current thread. isInterrupted() is an instance method which checks the Thread object that it is called on.

A common error is to call a static method on an instance.

Thread myThread = ...;
if (myThread.interrupted()) {} // WRONG! This might not be checking myThread.
if (myThread.isInterrupted()) {} // Right!

Another difference is that interrupted() also clears the status of the current thread. In other words, if you call it twice in a row and the thread is not interrupted between the two calls, the second call will return false even if the first call returned true.

The Javadocs tell you important things like this; use them often!

81
ответ дан 7 November 2019 в 07:46
поделиться

If you use interrupted, what you're asking is "Have I been interrupted since the last time I asked?"

isInterrupted tells you whether the thread you call it on is currently interrupted.

34
ответ дан 7 November 2019 в 07:46
поделиться

The interrupted() method is a class method that always checks the current thread and clears the interruption "flag". In other words, a second call to interrupted() will return false.

The isInterrupted() method is an instance method; it reports the status of the thread on which it is invoked. Also, it does not clear the interruption flag. If the flag is set, it will remain set after calling this method.

7
ответ дан 7 November 2019 в 07:46
поделиться

Here are a couple of examples of how you might use these methods:

  1. If you were writing your own thread pool, you might want to check the interrupted status on one of the threads that you are managing. In that case, you would call managedThread.isInterrupted() to check it's interrupted status.

  2. If you are writing your own InterruptedException handlers that don't immediately retrigger an equivalent exception via Thread.currentThread().interrupt() (for example, you might have a finally block after your exception handlers), you might want to check whether that thread that you are currently running on has been interrupted via an outside call or InterruptedException. In that case, you would check the boolean value of Thread.interrupted() to check on the status of your current thread.

The second method is really only ever useful to me in situations where I'm afraid that someone has written an exception eater at a lower level that, by extension, has eaten an InterruptedException as well.

4
ответ дан 7 November 2019 в 07:46
поделиться

Прерывание потока в Java рекомендуется. Если вы вызовете Thread.interrupt (), он установит флаг и отменит все невыполненные задачи ввода-вывода (что вызовет InterruptedException). Однако это зависит от кода, который выполняется в потоке, чтобы справиться с этим. Это называется реализацией политики прерывания потока.

Однако, поскольку состояние прерывания потока является общим, важно, чтобы любая такая обработка была потокобезопасной. Вы не хотите, чтобы какой-то другой поток запускался и пытался что-то сделать с флагом прерывания, если вы его обрабатываете. По этой причине флаг Thread.interrupted () делает его атомарным, поэтому он используется, когда вы хотите сказать: «Если этот поток был прерван, я собираюсь с ним разобраться). Обычно это включает очистку некоторых ресурсов. Как только вы закончите, вам, вероятно, следует распространить флаг прерывания, чтобы вызывающие абоненты могли его обработать. Вы можете сделать это, вызвав Thread.interrupt.

4
ответ дан 7 November 2019 в 07:46
поделиться

Метод interrupted () - это статический метод класса thread, который проверяет текущий поток и сбрасывает «флаг» прерывания. второй вызов interrupted () вернет false.

Метод isInterrupted () - это метод экземпляра; он сообщает о состоянии потока, в котором он был вызван. он не сбрасывает флаг прерывания.

Если флаг установлен, он останется установленным после вызова этого метода.

Thread myThread = ...;
if (myThread.interrupted()) {} //error

Thread.interrupted()//right

if (myThread.isInterrupted()) {} // Right
2
ответ дан 7 November 2019 в 07:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: