一.interrupt方法的作用
interrupt方法只能终止线程的阻塞状态(wait,join,sleep),在阻塞处抛出
InterruptedException异常,并不能终止运行的线程本身。
interrupt方法会改变线程的中断标志位。
1.interrupt方法可以终止运行态的线程吗?
public class ThreadInterrupt {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();
t.interrupt();
}
//打印线程
public static class MyThread extends Thread{
@Override
public void run() {
int i=0;
while(true){
i++;
System.out.println("run:"+i);
}
}
}
}
我们发现,打印线程会一直运行下去,interrupt方法并不能终止运行的线程本身。
2.线程处于sleep状态,被中断
public class ThreadInterrupt {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();
t.interrupt();
}
public static class MyThread extends Thread{
@Override
public void run() {
int i=0;
while(true){
i++;
System.out.println("run:"+i);
try {
sleep(5000);
} catch (InterruptedException e) {
System.out.println("被中断,返回");
break;
}
}
}
}
}
阻塞状态被中断
线程处于阻塞状态时,接收到中断信号,在阻塞处抛出InterruptedException异常,我们捕获异常之后,如果还有后续处理逻辑的话,后续处理逻辑会继续执行。
二.interrupted方法和isInterrupted方法
isInterrupted方法用来判断线程的中断状态,返回true或者false
public class ThreadInterrupt2 {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();
t.interrupt();
}
public static class MyThread extends Thread{
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("我进入了中断线程的条件中,将要结束run方法");
break;
} else {
System.out.println("我没有收到中断信息");
}
}
}
}
}
打印截图:
中断并不代表强迫终止一个线程,它是一种协作机制,是给线程传递一个取消的信号,但是让线程来决定如何以及何时退出。
isInterrupted ()很老实,只查询中断标志位,不改变中断标志位,而静态方法interrupted会改变中断位。
我们改下代码,看下运行结果:
public class ThreadInterrupt2 {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();
t.interrupt();
}
public static class MyThread extends Thread{
@Override
public void run() {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("isInterrupted的中断状态:"+this.isInterrupted());
System.out.println("interrupted的中断状态:"+Thread.interrupted());
System.out.println("isInterrupted的中断状态:"+this.isInterrupted());
break;
} else {
System.out.println("我没有收到中断信息");
}
}
}
}
}
\
\