首页 > 代码库 > [Java Basics] multi-threading

[Java Basics] multi-threading

1, Interrupt

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.

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.

Some API methods have built in interrupt handling. Of the top of my head this includes.

  • Object.wait()/Thread.sleep()
  • Most java.util.concurrent structures
  • Java NIO (but not java.io) and it does NOT use InterruptedException, instead using ClosedByInterruptException.

Interrupts are not explicitly handled by synchronization - synchronous blocks only gaurantee that, while executing, the block cannot be reentered by another thread.

总结: 对于像sleep()这样的方法,会自己throw InterrupttedException,程序会退出。

或者自己调用Thread.interrupted()方法检测Interrupted status并进行处理。

对于一般的synchronized method,不会自动处理Interrupt并退出。