interrupt,顾名思义,即中断的意思。单独调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常, 也就说,它可以用来中断一个正处于阻塞状态的线程;另外,通过interrupt方法和isInterrupted()方法来停止正在运行的线程。具体参照实例:
package nc.com.thread.traditional.example;
/**
* interrupt,顾名思义,即中断的意思。
* 单独调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常,
* 也就说,它可以用来中断一个正处于阻塞状态的线程;另外,
* 通过interrupt方法和isInterrupted()方法来停止正在运行的线程。
* @ClassName: TestInterrupt
* @Description: TODO(这里用一句话描述这个类的作用)
* @author A18ccms a18ccms_gmail_com
* @date 2015-12-19 下午07:07:53
*
*/
public class TestInterrupt {
public static void main(String[] args) throws Exception {
TestInterrupt test = new TestInterrupt();
中断处于阻塞的线程,同时会有异常
MyBlockThread thread = test.new MyBlockThread();
thread.start();
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
}
thread.interrupt();
//中断处于运行中的线程
//从这里可以看出,通过interrupt方法可以中断处于阻塞状态的线程。那么能不能中断处于非阻塞状态的线程呢?
//运行该程序会发现,while循环会一直运行直到变量i的值超出Integer.MAX_VALUE。所以说直接调用interrupt方法不能中断正在运行中的线程。
//但是如果配合isInterrupted()能够中断正在运行的线程,因为调用interrupt方法相当于将中断标志位置为true,那么可以通过调用
//isInterrupted()判断中断标志是否被置位来中断线程的执行。比如下面这段代码:
MyRunningThread r = test.new MyRunningThread();
r.start();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}
if(r.isAlive()){
r.interrupt();
}
}
class MyBlockThread extends Thread{
@Override
public void run() {
try {
System.out.println("进入睡眠状态");
Thread.currentThread().sleep(10000);
System.out.println("睡眠完毕");
} catch (InterruptedException e) {
//可以在线程处于阻塞状态下被中断时处理数据
System.out.println("得到中断异常");
}
System.out.println("run方法执行完毕");
}
}
class MyRunningThread extends Thread{
@Override
public void run() {
try {
while(true){
System.out.println("MyRunningThread running----------------状态");
if(isInterrupted()){
//在这里面接受处理线程终止命令,如数据备份持久化等
System.out.println("MyRunningThread 正在终止正在运行的线程");
}
}
} catch (Exception e) {
System.out.println("MyRunningThread 得到中断异常");
}
System.out.println("MyRunningThread run方法执行完毕");
}
}
}