如何中断线程
已经被抛弃的方法
- 通过调用stop()方法停止线程 //太暴力
- 通过调用suspend()和resume()方法
目前使用的方法
- 调用interrupt(),通知线程应该中断了
1、如果线程处于被阻塞状态,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常。
2、如果线程处于正常活动状态,那么会将该线程的中断标志设置为true。被设置中断标志的线程将继续正常运行,不受影响。 - 需要被调用的线程配合中断
1、在正常运行任务时,经常检查本线程的中断标志位,如果被设置了中断标志就自行停止线程。
2、如果线程处于正常活动状态,那么会将线程的中断标志设置为true。被设置中断标志的线程将继续正常运行,不受影响。
package com.interview.javabasic.thread;
public class InterruptDemo {
public static void main(String[] args) throws InterruptedException {
Runnable interruptTask = new Runnable() {
@Override
public void run() {
int i = 0;
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(100);
i++;
System.out.println(Thread.currentThread().getName() + "(" + Thread.currentThread().getState() + ") loop" + i);
}
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "(" + Thread.currentThread().getState() + ") catch Inter");
}
}
};
Thread t1 = new Thread(interruptTask, "t1");
System.out.println(t1.getName() + "("+t1.getState()+") is now");
t1.start();
System.out.println(t1.getName() + "("+t1.getState()+") is stop");
Thread.sleep(300);
t1.interrupt();
System.out.println(t1.getName() + "(" + t1.getState() + ") is interrupted");
Thread.sleep(300);
System.out.println(t1.getName() + "("+t1.getState()+") is inter now");
}
}