欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一个例子说明Thread interrupt() interrupted() isInterrupted()三个方法关系和区别

程序员文章站 2022-07-12 18:37:07
...

直接贴上例子

 

public class InteruptTest extends Thread {
	static int i = 0;

	@Override
	public void run() {
		while (!Thread.currentThread().isInterrupted()) {
			// i happy run , please break me
			System.out.println("I'm runing " + i++);
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();//①:发出中断请求,设置中断状态
				System.out.println(Thread.currentThread().isInterrupted());//②:判断中断状态(不清除中断状态)
				System.out.println(Thread.interrupted());//③:判断中断状态(清除中断状态)
			}
			System.out.println("current thread haven't been broken");
		}

	}

	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new InteruptTest();
		t1.start();
		Thread.sleep(1000);
		t1.interrupt();
	}
}

 这里有几个关键点是:

 

①:调用Thread.currentThread().interrupt()方法并不会立刻中断当前线程,只有等当前线程阻塞在类似sleep和wait等操作上才会执行

②:interrupt()会发出中断命令,而isInterrupted()和interrupted()并不会发出中断线程的命令;

  isInterrupted()和interrupted()的区别在于 interrupted会清除中断的状态,所以上面实例程序    会一直运行。如果注释掉第三点(catch代码库第三条),则程序会在下一次到达sleep的时候终止