JAVA thread0.interrupt()方法

interrupt()只是改变中断状态而已,interrupt()不会中断一个正在运行的线程。这一方法实际上完成的是,给受阻塞的线程抛出一个中断信号,这样受阻线程就得以退出阻塞的状态。

更确切的说,如果线程被Object.wait, Thread.join和Thread.sleep三种方法之一阻塞,那么,它将接收到一个中断异常(InterruptedException),从而提早地终结被阻塞状态,调用interrupt()方法可以使线程退出wait join sleep方法!

线程A在执行sleep,wait,join时,线程B调用线程A的interrupt方法,的确这一个时候A会有InterruptedException 异常抛出来.但这其实是在sleep,wait,join这些方法内部会不断检查中断状态的值,而自己抛出的InterruptedException。如果线程A正在执行一些指定的操作时如赋值,for,while,if,调用方法等,都不会去检查中断状态,所以线程A不会抛出interruptedException,而会一直执行着自己的操作.当线程A终于执行到wait(),sleep(),join()时,才马上会抛出 InterruptedException.若没有调用sleep(),wait(),join()这些方法,即没有在线程里自己检查中断状态自己抛出InterruptedException的 话,那InterruptedException是不会被抛出来的。

for example:

package com.tonyluis;

public class testInterrupt {
	public static void main(String[] args) {
		Thread t0 = new Thread(new task0(), "Thread0");
		Thread t1 = new Thread(new task1(t0), "Thread1");
		t0.start();
		t1.start();
	}
}

class task0 implements Runnable {
	public void run() {
		String currentThreadName = Thread.currentThread().getName();
		for(int i=0;i<Integer.MAX_VALUE;i++){
			//耗时运算
		}
		try {
			System.out.println(currentThreadName + ".interrupted()=" + Thread.currentThread().isInterrupted());
			System.out.println(currentThreadName+" is Sleep.");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			System.out.println(currentThreadName + ".interrupted()=" + Thread.currentThread().isInterrupted());
		}
		System.out.println(currentThreadName + " end!");
	}
}

class task1 implements Runnable {
	Thread thread;

	task1(Thread thread) {
		this.thread = thread;
	}

	public void run() {
		String currentThreadName = Thread.currentThread().getName();
		System.out.println(thread.getName() + ".interrupted()=" + thread.isInterrupted());
		thread.interrupt();
		System.out.println(currentThreadName + " set " + thread.getName() + " to be Interrupted");
		System.out.println(thread.getName() + ".interrupted()=" + thread.isInterrupted());
		System.out.println(currentThreadName + " end!");
	}
}

 输出:

Thread0.interrupted()=false
Thread1 set Thread0 to be Interrupted
Thread0.interrupted()=true
Thread1 end!
Thread0.interrupted()=true
Thread0 is Sleep.
Thread0.interrupted()=false
Thread0 end!

原文地址:https://www.cnblogs.com/tonyluis/p/5531757.html