你真的了解Thread中的interrupt和Stop吗?

第一次在简书写文章,其实还是蛮紧张的,之前一直是在博客园写文章,之所以这次选择这里,原因是在工作遇到很多问题,多数中都是在简书中找到了解决问题的方法。这次算是感谢也是一种学习,同时也是希望能帮助到更多人。

我不确定看到这篇文章的人群中都是工作多久的,也许是刚入门小白,也许是驰骋代码界数年的高级攻城狮,也许是雄霸一方的大佬。如下内容仅仅是我对Thread的一些理解欢迎批评指正。

Thread中的Stop方法根据官方的定义则是为了结束和停止一个线程的运行,这个可以通过以下代码得到证实。

定义StopThread测试类

    static class StopThread extends Thread{

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 100; i++) {
                System.out.println("count: " + i);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Main方法测试

    public static void main(String[] args) {
        StopThread stopThread = new StopThread();
        stopThread.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopThread.stop();
    }

结果如下

count: 0
count: 1
count: 2
Process finished with exit code 0

以上代码如果不对运行线程执行Stop操作,count输出一定是到count:99的。由于执行了Stop操作,所以线程被直接终止。

我们在看Interrupt方法(现在在真正开发中Java也推荐我们去使用Interrupt替换Stop,并且Stop方法也被标记为过时方法),单说方法本身含义是打断线程运行,那么真实运行上效果如何?
同样我们粘出我们的测试代码

    static class InterruptThread extends Thread{

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 100; i++) {
               System.out.println("count: " + i);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Main方法代码如下:

    public static void main(String[] args) {
        InterruptThread interruptThread = new InterruptThread();
        interruptThread.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        interruptThread.interrupt();
    }

根据如上代码我们看下替换Stop之后的Interrupt方法执行结果

count: 0
count: 1
count: 2
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.gsafety.javalib.Test$InterruptThread.run(Test.java:24)
count: 3
count: 4
count: 5
count: 6
count: 7
count: 8
count: 9
....
count: 95
count: 96
count: 97
count: 98
count: 99
Process finished with exit code 1

从运行结果看Interrupt方法并未中断或者结束线程运行,那么既然如此为何Java推荐使用Interrupt来替换Stop方法那?
其实对于方法Interrupt而言,真实意义并不是用来结束当前线程,否则为何要废弃Stop方法?Interrupt方法仅仅是对当前线程做了中断‘标记’,但是否真的结束线程运行,并不是由Java来完成的,需要开发者自己判断此标记,适当位置时机结束线程运行。

这里我们依然采用代码的方式来验证我的猜想!!!修改如上InterruptThread类代码!!!

    public static void main(String[] args) {
        InterruptThread interruptThread = new InterruptThread();
        interruptThread.start();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        interruptThread.interrupt();
    }


    static class InterruptThread extends Thread{

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 100000; i++) {
                if(isInterrupted())
                    return;
               System.out.println("count: " + i);
            }
        }
    }

运行结果如下

count: 0
count: 1
count: 2
count: 3
count: 4
count: 5
...
count: 3437
count: 3438
count: 3439
count: 3440
>>>>>>>>>>>>>>>Interrupted<<<<<<<<<<<<<<<<<<<
Process finished with exit code 0

到这里基本也就验证了我们的猜想,Interrupt方法仅仅还是起到了一个标记中断线程状态作用,并且通过isInterrupted()判断线程状态。对比Stop方法这里是由开发者自己来选择在合适的时机完成线程的结束工作,更加符合开发需要,也更加人性化了。

细心的人也许会发现,在最后一轮测试中我们并未使用Thread的静态Sleep方法。那么我们来测试下,这里我们增加Sleep方法看下。

    public static void main(String[] args) {
        InterruptThread interruptThread = new InterruptThread();
        interruptThread.start();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        interruptThread.interrupt();
    }


    static class InterruptThread extends Thread{

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 100; i++) {
                if(isInterrupted()) {
                    System.out.println(">>>>>>>>>>>>>>>Interrupted<<<<<<<<");
                    return;
                }
                System.out.println("count: " + i);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

这里看下输入日志

count: 0
count: 1
count: 2
count: 3
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.gsafety.javalib.Test$InterruptThread.run(Test.java:28)
count: 4
count: 5
count: 6
count: 7
count: 8
....
count: 97
count: 98
count: 99

Process finished with exit code 0

这个结果很显然和我们预期的是不一样。那么问题在哪里???这里说下Sleep方法,Sleep方法是被try{}catch(InterruptedException){}包裹,很显然这个异常捕获的意思表示Sleep方法存在被打断休眠的可能,不过他还有另一个作用是在休眠被打断之后,修改中断标记为False,这也就导致方法isInterrupted()判断无效的原因。

修改线程中断标记的不仅仅只有Sleep方法其实还有很多,例如wait()等(这里可以简单记录为会抛出InterruptedException异常的方法)。

这里也许会有人疑惑,真实场景应用中wait方法是真实存在的,如果线程真的标记结束了,我们如何判断?这里可以看上面代码5行,如果线程被中断无论是否在Sleep方法执行之前又或者在Sleep方法执行中,在执行Sleep方法都会立即抛出InterruptException,避免过多的消耗资源,我们可以在catch代码块中做资源的收尾和线程结束工作。

这里在补充说下先线程Thread的静态方法interrupted(),作用是判断线程是否被标记为中断。该方法会在一次判断之后会修改线程标记状态(效果和Sleep方法一样)。

这里我们依然用代码来说明问题

    public static void main(String[] args) {
        InterruptThread interruptThread = new InterruptThread();
        interruptThread.start();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        interruptThread.interrupt();
    }


    static class InterruptThread extends Thread{

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 100000; i++) {
                if(Thread.interrupted()) {
                    if (isInterrupted()) {
                        System.out.println(">>>>>>>>>>>>>>>Interrupted<<<<<<<<");
                        return;
                    }
                }
               System.out.println("count: " + i);
            }
        }
    }

运行结果

count: 0
count: 1
count: 2
count: 3
....
count: 99995
count: 99996
count: 99997
count: 99998
count: 99999

Process finished with exit code 0

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容