package com.demo.concurrent.thread;
/**
* 线程中断:线程间协作的一种方式
*
* interrupt() 方法:中断标志,设置中断标志为true,等待线程自行停止。
*
* isinterrupted()方法:判断是否中断,如果中断,则返回true,否则返回false
*
* 重要:
* interrupted()方法:判断是否中断,并清除中断标志。他是一个静态方法,表示的是当前线程的中断状态。
* threada.interrupted() 等价于 Thread.interrupted();
*
* @author
*
*/
public class ThreadInterrupt implements Runnable{
public void run() {
//返回true 表明当前线程已经被interrupted
System.out.println("4:"+Thread.currentThread().isInterrupted());
//返回true 表明当前线程已经被interrupted
System.out.println("5:"+Thread.interrupted());
for(int i=0;i<1000000000;i++) {
}
}
public static void main(String[] args) throws InterruptedException {
Thread threada = new Thread(new ThreadInterrupt());
threada.start();
threada.interrupt();
//返回true,表明当前线程已经被interrupted
System.out.println("1:"+threada.isInterrupted());
//返回false ,表明当前主线程未被interrupted
System.out.println("2:"+threada.interrupted());
//返回false。因为在内部调用了interrupted方法,之后中断标志被清除
System.out.println("3:"+threada.isInterrupted());
}
}
执行结果:
1:true
4:true
2:false
5:true
3:false
注意:执行结果有不确定性,因为,主线程和子线程,在同时工作,结果会因为两个线程的执行速度的不通而不同