API详解

3种方法都是Thread类的API

方法描述
public void interrupt()中断调用该方法的线程,此处的中断不是线程就会done,而只是添加中断标志位,线程该往下执行还是会执行的
public boolean isinterrupted()测试调用该方法的线程是否已被中断,不会清除中断标志位,其实就是测试中断标志位是否存在
public static boolean interrupted()Thread.interrupted(),使用该静态方法的线程是否已被中断;会清除中断标志位,也就说,第一次调用返回true,再接着调用第二次会返回false,除非在第二次调用前又设置了中断位
1、 interrupt()

在一个线程中调用另一个线程的interrupt()方法,即会向那个线程发出信号——线程中断状态已被设置。至于那个线程何去何从,由具体的代码实现决定;
当然,一个线程也可以中断自己;
如果线程正处于被阻塞状态(线程内调用sleep、wait、join),那么线程将立即退出被阻塞状态,并且会清除中断状态,并抛出了一个InterruptedException异常;如果线程没有被阻塞,这时调用 interrupt()将不起作用,直到执行到wait(),sleep(),join()时,才马上会抛出 InterruptedException。

2、isinterrupted()
public static void main(String[] args) {
	Thread thread= new Thread(new Runnable() {
		@Override
		public void run() {
			System.out.println("isInterrupted " + Thread.currentThread().isInterrupted()); // true
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("isInterrupted " + Thread.currentThread().isInterrupted()); // false
			System.out.println(Thread.currentThread().getName() + "运行结束");
		}
	});
	thread.start();
	thread.interrupt();
	System.out.println(Thread.currentThread().getName() + "运行结束");
}
main运行结束
isInterrupted true
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at com.spring.demo.javabase.thread.ThreadOperation$1.run(ThreadOperation.java:25)
	at java.lang.Thread.run(Thread.java:748)
isInterrupted false
Thread-0运行结束

可以看到,在主线程中调用子线程的interrupt()方法,在run方法中isInterrupted()获取到的结果为true,子线程设置了中断标志,sleep()时被打断抛出InterruptedException并清除中断标志位,因此第二次是isInterrupted()返回的结果是false

3、interrupted()

interrupted()方法是Thread的静态方法,其实它和isinterrupted()方法底层调用的都是private native boolean isInterrupted(boolean ClearInterrupted)
区别在于isinterrupted() 调用时参数boolean ClearInterrupted传递的是false,也就是说不会清除中断位;
而相反,interrupted()传递的是true,调用会清除中段位的

public static void main(String[] args) {
	Thread thread= new Thread(new Runnable() {
		@Override
		public void run() {
			System.out.println("Thread.interrupted() " + Thread.interrupted()); // true
			System.out.println("isInterrupted second " + Thread.currentThread().isInterrupted()); // false
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "运行结束");
		}
	});
	thread.start();
	thread.interrupt();
	System.out.println("isInterrupted first " + thread.isInterrupted()); // true
	System.out.println(Thread.currentThread().getName() + "运行结束");
}
isInterrupted first true
main运行结束
Thread.interrupted() true
isInterrupted second false
Thread-0运行结束

可以看到中断后第一次isInterrupted() 返回true,在run方法中调用interrupted()同样会返回true但同时会清除中断标志,所有sleep()不会被打断,并且第二次执行isInterrupted() 会返回false

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐