Thread interrupt
线程中断有3个重要的方法:
thread.interrupt() 给目标线程发送中断信号,目标线程中断标记置为true.
thread.isInterrupted() 返回目标线程的中断标记
thread.interrupted() 返回目标线程的中断标记,并将其置为false。
调用Thread.interrupt() 用于请求另外一个线程中止执行,而不是直接中止
调用线程的interrupt方法,只有当线程走到了sleep, wait, join等阻塞这些方法的时候,才会抛出InterruptedException
package test; public class Sys extends Thread { private boolean stop = false; public static void main(String[] args) throws InterruptedException { Sys thread = new Sys(); thread.start(); Thread.sleep(3000); thread.interrupt(); Thread.sleep(3000); System.out.println("Stopping application"); } @Override public void run() { while (!stop) { System.out.println("Thread is running ... "); } System.out.println("Thread exiting under request"); } }
线程被发送了中断信号,但是没有逻辑去处理这段信号。所以线程会一直运行。
package test; public class Sys extends Thread { private boolean stop = false; public static void main(String[] args) throws InterruptedException { Sys thread = new Sys(); thread.start(); Thread.sleep(3000); thread.interrupt(); Thread.sleep(3000); System.out.println("Stopping application"); } @Override public void run() { while (!stop) { System.out.println("Thread is running ... "); if (Thread.currentThread().isInterrupted()) { // 处理线程中断的逻辑 break; } } System.out.println("Thread exiting under request"); } }
Thread is running ...
Thread is running ...
...........
Thread is running ...
Thread is running ...
Thread exiting under request
Stopping application
通过判断是否有中断信号则能中断成功
package test; public class Sys extends Thread { private boolean stop = false; public static void main(String[] args) throws InterruptedException { Sys thread = new Sys(); thread.start(); Thread.sleep(3000); thread.interrupt(); Thread.sleep(3000); System.out.println("Stopping application"); } @Override public void run() { while (!stop) { System.out.println("Thread is running ... "); try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("Exception:" + e.getMessage()); if(Thread.currentThread().isInterrupted()){ // 处理线程中断的逻辑 break; } } } System.out.println("Thread exiting under request"); } }
Thread is running ...
Thread is running ...
Exception:sleep interrupted
Thread is running ...
Thread is running ...
Stopping application
Thread is running ...
Thread is running ...
......
打印中断后继续执行。
原因:sleep()函数执行时,若线程被中断,会抛出中断异常,并且中断符号位会清除(置false)
* @throws InterruptedException * if any thread has interrupted the current thread. The * <i>interrupted status</i> of the current thread is * cleared when this exception is thrown. */ public static native void sleep(long millis) throws InterruptedException;

浙公网安备 33010602011771号