三种不同的interrupt方法区别调用

PART1:关于 Thread.interrupted() 和thread.isInterrupted()的重置标识状态区别

  1. Thread.interrupted()方法:通过类调用
  2. thread.isInterrupted()方法:通过对象调用

interrupted()源码
Thread.interrupted()方法:通过类调用
判断当前线程是否处于中断状态在这里插入图片描述

isInterrupted()源码
thread.isInterrupted()方法:通过对象调用
判断调用该函数的线程是否处于中断状态
在这里插入图片描述
interrupted()是静态方法:内部实现是调用的当前线程的isInterrupted(),并且会重置当前线程的中断状态
isInterrupted()是实例方法,是调用该方法的对象所表示的那个线程isInterrupted(),不会重置当前线程的中断状态

测试方法验证:

1.在这里插入图片描述

第一个红框中断的线程是我们自己创建的myThread线程,我调用的interrupted(),由上面源码可知是判断当前线程的中断状态,当前线程是main线程,我根本没有中断过main线程,所以2次调用均返回“false”
2.在这里插入图片描述

第一个红框中断的线程是当前线程(main线程),我调用的interrupted(),由上面源码可知是判断当前线程的中断状态,当前线程是main线程,所以第1次调用结果返回“true”,因为我确实中断了main线程,
由源码可知interrupted()调用的是isInterrupted(),并会重置中断状态,所以第一次调用之后把中断状态给重置了,从中断状态重置为非中断状态,所以第2次调用的结果返回“false”

3.在这里插入图片描述

第一个红框中断的线程是我们自己创建的myThread线程,我调用的isInterrupted(),由上面源码可知是判断执行该方法的对象所表示线程的中断状态,也就是myThread引用所表示的线程的中断状态,所以第1次调用结果返回“true”。由源码可知isInterrupted()不会重置中断状态,所以第一次调用之后没有把中断状态给重置(从中断状态重置为非中断状态),所以第2次调用的结果还返回“true”

在这里插入图片描述

第一个红框中断的线程是我们自己创建的myThread线程,我调用的isInterrupted(),由上面源码可知是判断执行该方法的对象所表示线程的中断状态,也就是main的中断状态,我压根没有中断main线程,所以理所当然2次调用结果都返回“false”

5.在这里插入图片描述

第一个红框中断的线程是当前线程(main线程),我调用的isInterrupted(),由上面源码可知是判断执行该方法的对象所表示线程的中断状态,也就是main的中断状态,所以第1次调用结果返回“true”,因为源码内部调用isInterrupted() 参数传的false,不会重置main线程的中断状态,所以第2次调用还是返回”true”

该部分请参考原创博主:https://blog.csdn.net/zhuyong7/article/details/80852884

PART2:interrupt方法中断线程的原理

Thread类的interrupt方法是用来中断一个线程的。
interrupt()方法不像stop方法强行终止一个线程。它只是把要被停止的线程设置成中断状态。而此时要被中断的线程是可以继续执行的。

class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<5000; i++){
            System.out.println("i="+(i+1));
        }
    }
}
public class Run {
    public static void main(String args[]){
        Thread mythread = new MyThread();
        mythread.start();
        try {
            Thread.sleep(10);
            System.out.println("执行interrput()方法");
            mythread.interrupt();
            System.out.println("mythread线程的状态标识位:"+mythread.isInterrupted());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
输出结果:
...
i=105
i=106
执行interrput()方法
i=107
i=108
mythread线程的状态标识位:true
i=109
i=110
......
i=4999
i=5000

从输出结果可以看出,被中断的线程并没有停止执行。
根据输出结果阐述cpu中main线程和子线程的执行过程:

  1. 程序从main入口函数执行,创建出子线程后,main线程就开始休眠10ms,子线程在这10ms内拥有cpu的使用权,进行i的输出;
  2. 当i=106时,10ms结束,主线程main获得cpu的使用权:执行interrput()方法
  3. 调用interrput()方法后,子线程再次抢占cpu打印i=107,i=108后。又被main线程抢占cpu。输出mythread线程的状态标识位:true。
  4. main线程结束,子线程获得cpu使用权。接着打印i=109…i=5000

关于windows和unix下cpu的使用机制参考上篇博文链接:https://blog.csdn.net/renhrong/article/details/106540365

对于打印结果的解释说明:
Q:明明调用了mythread.interrupt();方法中断子线程并且显示mythread线程的状态标识位为true,也就是被中断了,子线程为什么还能继续执行直至打印结束i=5000?

A: 原理:
实际上,mythread.interrupt();方法的中断仅仅是给调用的线程对象做一个标记而已。称为中断标志,中断标志默认为false;在线程调用自己的t.interrupt()方法以后,此线程中断标志就为true。也就是mythread线程调用mythread.interrupt()方法后,mythread线程的中断标志就修改为true。但实际上不会对正常运行的线程产生影响,因为正常运行的线程(如例中的mythread线程)不会去检查自己的中断标志,只有那些被阻塞的线程会不停的检查自己的中断标志,这个阻塞包括因为wait,join,yield,sleep而处于未运行状态的线程这些阻塞的线程检查到自己的中断标记为true,就会抛出interruptedException异常

PART3:使用interrupt方法中断线程用例

1.interrupt中断的线程可以继续执行

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            System.out.println("i="+(i+1));
        }
    }
}
public class Run {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
输出结果:
...
i=499994
i=499995
i=499996
i=499997
i=499998
i=499999
i=500000

从输出结果可以看出,被中断的线程并没有停止执行。它只是把要被停止的线程设置成中断状态。而此时要被中断的线程是可以继续执行的。

2.被中断的线程可以通过isInterrupted()或者是interrupted()方法判断当前线程的中断状态是否标志为中断,然后终止线程。

public class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            if(Thread.interrupted()) {
                System.out.println("线程已经终止, for循环不再执行");
                break;
            }//if语句为新增模块
            System.out.println("i="+(i+1));
        }
    }
}
public class Run {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

输出结果:
...
i=202053
i=202054
i=202055
i=202056
线程已经终止, for循环不再执行。

执行流程:
1.进入main函数,执行main函数中的语句,创建子线程,然后mian线程休眠2s
2.子线程获取cpu资源,输出打印i
3.休眠结束后,main线程和子线程争夺cpu,main线程获取cpu执行thread.interrupt()语句。子线程的标志位信息由false变为true
4.mian线程执行完成,子线程占据cpu。准备继续执行,但是进入for循环打印输出前进行if语句判断------>if(Thread.interrupted())为true,打印

线程已经终止, for循环不再执行。

跳出循环

3.上面的示例虽然停止了线程,但是如果for语句后面还有语句,这些语句还是会继续。看下面的例子:

 class MyThread extends Thread {
    public void run(){
        super.run();
        for(int i=0; i<500000; i++){
            if(Thread.interrupted()) {
                System.out.println("线程已经终止, for循环不再执行");
                break;
            }
            System.out.println("i="+(i+1));
        }

        System.out.println("这是for循环外面的语句");//新增
    }
}

public class test {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
使用Run.java执行的结果是:
...
i=180136
i=180137
i=180138
i=180139
线程已经终止, for循环不再执行
这是for循环外面的语句

执行流程和例2一样

4.如何解决语句继续运行的问题? 看一下更新后的代码:

class MyThread extends Thread {
    public void run(){
        super.run();
        try {
            for(int i=0; i<500000; i++){
                if(Thread.interrupted()) {
                    System.out.println("线程已经终止, for循环不再执行");
                    throw new InterruptedException();//把braek换成了throw抛出异常
                }
                System.out.println("i="+(i+1));
            }
            System.out.println("这是for循环外面的语句");
        } catch (InterruptedException e) {
            System.out.println("进入MyThread.java类中的catch了。。。");
            e.printStackTrace();
        }
        System.out.println("在run方法最外层的语句");
    }
}
public class test {
    public static void main(String args[]){
        Thread thread = new MyThread();
        thread.start();
        try {
            Thread.sleep(2000);
            thread.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
输出结果:
...
i=261142
i=261143
i=261144
i=261145
i=261146
i=261147
线程已经终止, for循环不再执行
进入MyThread.java类中的catch了。。。
在run方法最外层的语句
java.lang.InterruptedException
	at MyThread.run(test.java:8)

执行流程类似2,3

public class ThreadMethod {
    public static void main(String[] args) {
        //实例化Runnable实例
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + ":子线程开始");
                while (!Thread.currentThread().isInterrupted()) {
                    //参数默认是false,这个方法不会清除中断状态
                    try { 
                        Thread.sleep(1000);//让子线程休眠1s再打印
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        // break;
                    }
                    System.out.println("子线程任务执行");//while循环之内
                }

                System.out.println(Thread.currentThread().getName() + ":子线程结束");//run方法之内,while循环之外
            }
        };
        /实例化runnable实例完成///
        System.out.println (Thread.currentThread().getName() + ":主线程开始");
        Thread son_thread = new Thread(runnable);//自主创建的子线程
        son_thread.start();//子线程开始
        try {
            Thread.sleep(4500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }//休眠是让当前主线程休眠,不再占有cpu,休眠4.5秒后再进行中断子线程操作 son_thread.interrupt();
        son_thread.interrupt();//中断子线程
        System.out.println(Thread.currentThread().getName() + ":主线程结束");
    }
}

打印结果:
在这里插入图片描述
执行流程:
1.从main函数进入,main线程执行。打印“main:主线程开始”,接着mian线程中创建并且启动子线程,进入sleep模式,休眠4.5s,在未来的4.5s内不参与cpu的争夺
2.在mian线程休眠的4.5s内,子线程获得cpu资源,开始执行子线程,因此打印出:Thread-0:子线程开始。进入while循环,每休眠1s,打印一句“子线程任务执行”。一共打印了四句子。用时4s。当子线程处于第5次休眠时(此时4-5s处于休眠状态),main线程经过4.5s的休眠被唤醒。
3.main线程抢占cpu资源执行son_thread.interrupt();中断子线程,并打印main:主线程结束
4.在3中,主线程调用son_thread.interrupt()中断子线程时,子线程正处于休眠状态(4-5s)。由PART1中interrupt方法原理可知:*该方法的调用使得子线程的标识位变为true并且子线程处于sleep状态,此时子线程会检查自己的标识位。查出发生了改变,抛出异常:java.lang.InterruptedException: sleep interrupted
5.异常抛出以后还在持续打印“子线程执行任务的原因:”这点非常重要,我原来想了很久一直都没想对!!!
原来错误的想法:调用interrupt操作以后,已经修改了子线程的标识位,而子线程处于sleep阻塞状态,因此会抛出异常。由于标识位的修改,那么调用Thread.currentThread().isInterrupted()函数得到的结果为true;也就是说while(!Thread.currentThread().isInterrupted())while语句中为false;while语句不执行;那么函数就不会再打印““子线程执行任务”;而实跳出while循环,打印“子线程结束”。但是实际上却是一直在死循环打印“子线程执行任务”。
一直在死循环打印“子线程执行任务”的原因:
在sleep操作中,sleep是检验到了标识位的修改,接收到了这个中断。之后他才会抛出异常。而这里面sleep操作,已经通过try-catch的catch语句块把这个interrupted exception异常捕获,所以对于中断发生的异常是在这个catch里面已经做了处理。因此对程序而言,它捕获了一次之后,再次进入while循环,由于isInterrupt()它仅仅只是判断有没有发生中断。返回是布尔类型,上述中断已经做了处理,所以这里方法调用的返回值为false;while内容为true;继续进行循环。她才会继续执行的。

所以我们要是想结束子线程可以在catch模块中添加break操作。一旦捕获到异常,通过break跳出while循环,就不再执行
在这里插入图片描述

那么如果想要通过中断来结束子线程怎么办呢??
此时外面就不要用while(!Thread.currentThread().isInterrupted()操作了;而是把异常直接往外抛,而不是用try-catch语句中的catch捕获到。比如例子4.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值