中断只是线程的标识位属性,表示一个运行中的线程是否被其他线程进行了中断操作,线程并不会立即停止的,只是打上一个标识位,其他线程通过调用线程的interrupt()方法会执行这种操作,线程通过方法isInterrupted()来判断是否被中断。
判断线程是否是停止状态:
1. This.interrupted()测试当前线程是否已经中断
2. This.isInterupted()测试线程是否已经中断,返回值都是boolean
区别:
1. interrupted() 方法用于测试当前线程是否中断,当前线程指的是运行this.interrupted()代码的线程
官方说明:
,如果对已经中断的线程调用两次interrupted方法,第一次返回true,第二次返回false,因为调用interrupted将中端标识位清除,所以第二次调用interrupted方法将返回false
2. 调用isInterrupted()方法并不会将中断标识位清除
Note:
1. interrupt方法给线程加上中断标识位,但是线程不会立刻停止
2. 声明抛出InterrupteException的方法例如sleep,wait方法,能够响应中断方法interrupt(),并抛出中断异常,在抛出异常前会把中断标识位清除,如果此时调用isInterrupted方法将返回false。
public class TestDemo {
public static void main(String[] args) {
ChildWork cw = new ChildWork();
cw.start();
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
cw.interrupt();
}
}
class ChildWork extends Thread{
@Override
public void run() {
try{
for(int i=0;i<10000;i++){
if(this.isInterrupted()){
break;
}
System.out.println("程序执行"+(i+1)+"次 ");
}
System.out.println("线程执行完毕....");
}catch(Exception e){
e.printStackTrace();
}
}
}
最后,还是会打印出 执行完毕。。。,说明interrupt()方法并不是立刻中断线程,如果我们想通过立刻中断线程,
可以直接抛出interrupteException。
异常中断线程:
public class MyThread3 extends Thread{
public static void main(String[] args) {
MyThread3 mt = new MyThread3();
mt.start();
try {
Thread.currentThread().sleep(10);
mt.interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
try{
for(int i=0;i<5000;i++){
if(this.currentThread().isInterrupted()){
System.out.println("线程是中断状态了");
throw new InterruptedException();
}
System.out.println("执行"+(i+1)+"次");
}
System.out.println("这句话不会去执行.....");
}catch(InterruptedException e){
e.printStackTrace();
System.out.println("捕获中断异常,线程停止");
}
System.out.println("try catch 后面的语句还是会执行的....");
}
}
,抛出interruptException的线程能够响应中断,但是try-catch后面的语句还是会执行。
,这种中断线程的方法,用处可能不大,因为 生吞了异常,只是将异常信息给打印出来,但是高层的代码无法去获取
异常发生的证据,我们可以,在捕获中断异常后,再给当前线程打上中断标识位,this.currentThread.interrupt(),表示中断的发生,便于高层代码的处理(关于这点,可以看下https://www.cnblogs.com/hapjin/p/5450779.html),这样就将异常向上传播了.