interrupt、interrupted和isInterrupted的区别

interrupt()、interrupted()和isInterrupted()的直观区别
  1. interrupt()

形式上中断一个线程,不会去真正意义上的打断一个正在运行的线程,而是修改当前线程的中断状态码。同时,对于处于sleep()、wait()和join()阻塞下的线程,该方法会使当前线程抛出一个线程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class App 
{
public static void main( String[] args )
{
Thread thread = new Thread(()->{
while(true){
System.out.println(Thread.currentThread().getName() + " 依旧在运行");
}

});
thread.start();
thread.interrupt();jieguo
}
}

运行结果如下:

interrupt测试结果

  1. isInterrupted()

该方法会返回线程的中断标志位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class App 
{
public static void main( String[] args )
{
Thread thread = new Thread(()->{
while(true){
}

});
thread.start();
System.out.println("中断前:" + thread.isInterrupted());
thread.interrupt();
System.out.println("中断后:" + thread.isInterrupted());
}
}

运行结果如下:调用某一个线程对象的isInterrupted()方法会返回该线程的中断状态码。调用interrupt()方法以后,会改变这个线程的中断状态码。

isInterrupted测试结果

  1. interrupted()

该方法会返回当前线程的中断标志位,同时会重置中断标志位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class App 
{
public static void main( String[] args )
{
Thread thread = new Thread(()->{
while(true){
if(Thread.interrupted()){
System.out.println("线程中断标志位为true");
}
}

});
thread.start();
System.out.println("中断前:" + thread.isInterrupted());
thread.interrupt();
System.out.println("中断后:" + thread.isInterrupted());
}
}

运行结果如下:

interrupt测试结果


interrupt、interrupted和isInterrupted的区别
http://www.muzili.ren/2022/06/11/intrrup、interrupted、isInterrupted/
作者
jievhaha
发布于
2022年6月11日
许可协议