分享

java中如何中断thread

 jasonbetter 2018-09-21

java中如何中断thread

要中断thread的执行,我们有多种方式,有些方式是推荐的,有些方式是不推荐的,甚至是错误的。


1. 可否用interrupt()方法来中断thread?

为了回答这个问题,我们首先来看一个例子:

  1. class MyThread implements Runnable {
  2. public void run() {
  3. while (true) {
  4. System.out.println("Mythread am running!, current interrupted status is " + Thread.currentThread().isInterrupted());
  5. }
  6. }
  7. }
  8. public class InterruptTaskTest {
  9. public static void main(String[] args) {
  10. Thread thread = new Thread(new MyThread());
  11. thread.start(); // start mythread
  12. //
  13. try {
  14. Thread.sleep(100); // the main thread sleeps for 100 miniseconds
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. System.out.println("Main thread tries to interrupt mythread!");
  19. thread.interrupt(); // "interrupt" mythread
  20. }
  21. }
输出:

Mythread is running!, current interrupted status is false
Main thread tries to interrupt mythread!
Mythread is running!, current interrupted status is true

Mythread is running!, current interrupted status is true
Mythread is running!, current interrupted status is true
Mythread is running!, current interrupted status is true

Mythread is running!, current interrupted status is true

从上面的结果可以看出,调用interrupt方法并不能使得一个thread终止,但是这个方法可以改变线程是否被终止的状态为true. 用一句社会上的话来讲就是”不错,老子是欠你钱,但是老子就是不还“。

既然线程的状态已经改变,那么我们可以加入下面一句话来让线程停止。

  1. class MyThread implements Runnable {
  2. public void run() {
  3. while (true) {
  4. System.out.println("Mythread is running!, current status is " + Thread.currentThread().isInterrupted());
  5. <strong> <span style="color:#ff0000;">if (Thread.currentThread().isInterrupted()) {
  6. System.out.println("Mythread stops");
  7. return;
  8. }</span></strong>
  9. }
  10. }
  11. }
  12. public class InterruptTaskTest {
  13. public static void main(String[] args) {
  14. Thread thread = new Thread(new MyThread());
  15. thread.start(); // start mythread
  16. try {
  17. Thread.sleep(50);
  18. } catch (InterruptedException e) {
  19. e.printStackTrace();
  20. }
  21. System.out.println("Main thread tries to interrupt mythread!");
  22. thread.interrupt(); // "interrupt" mythread
  23. }
  24. }

输出是:

Mythread is running!, current status is false
Mythread is running!, current status is false
Mythread is running!, current status is false
Main thread tries to interrupt mythread!
Mythread is running!, current status is false
Mythread is running!, current status is true
Mythread stops

你如果运行上面的代码,得到的结果有可能是:

Mythread is running!, current status is false
Mythread is running!, current status is false
Mythread is running!, current status is false
Main thread tries to interrupt mythread!
Mythread is running!, current status is false
Mythread stops

原因是当mythread打印 ”Mythread is running!, current status is false“这句话的时候,main thread并没有执行下面代码,

thread.interrupt();

如果当上面语句被执行以后,mythread执行if 条件语句,那么最后会输出 ”Mythread stops“。


从上面这个例子可以看出,通过interrupt()方法,我们还是可以让一个线程终止的。但是我们是不是就可以认为这是一个好的方法呢?回答是NO。因为interrupt方法里面有很多的陷阱,先读读下面这段话:

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

上面这句话的意思是如果线程处于阻塞状态(可能是因为调用了wait,join,sleep的原因),那么,如果你调用interrupt方法,那么你惨了,因为interrupt状态会被清除并且被抛出异常。如果你不理解这句话,看看下面的代码:

  1. class MyThread implements Runnable {
  2. public void run() {
  3. while (true) {
  4. System.out.println("Mythread is running!, current status is " + Thread.currentThread().isInterrupted());
  5. <span style="color:#ff0000;"> try {
  6. System.out.println("Mythread starts to sleep!");
  7. Thread.sleep(1000);
  8. System.out.println("Mythread wakes up!");
  9. } catch (InterruptedException e) {
  10. System.out.println("Throws exception!, current status is " + Thread.currentThread().isInterrupted());
  11. }</span>
  12. if (Thread.currentThread().isInterrupted()) {
  13. System.out.println("Mythread stops");
  14. return;
  15. }
  16. }
  17. }
  18. }
  19. public class InterruptTaskTest {
  20. public static void main(String[] args) {
  21. Thread thread = new Thread(new MyThread());
  22. thread.start(); // start mythread
  23. try {
  24. Thread.sleep(2);
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. }
  28. System.out.println("Main thread tries to interrupt mythread!");
  29. thread.interrupt(); // "interrupt" mythread
  30. }
  31. }

输出结果是:

Mythread is running!, current status is false
Mythread starts to sleep!
Main thread tries to interrupt mythread!
Throws exception!, current status is false
Mythread is running!, current status is false
Mythread starts to sleep!
Mythread wakes up!
Mythread is running!, current status is false
Mythread starts to sleep!
Mythread wakes up!
Mythread is running!, current status is false
Mythread starts to sleep!
Mythread wakes up!
Mythread is running!, current status is false
Mythread starts to sleep!
Mythread wakes up!
Mythread is running!, current status is false

从结果中可以看出,发生异常后,interrupt status 居然不是true, 即便interrupt方法已经调用了,所以后面部分的if 条件始终是false,线程最后没有能够停下来。

2. 什么是一种比较好的让线程停下来的方法呢?

方法代码如下:

  1. public class MyThread implements Runnable {
  2. private volatile boolean isRunning = true;
  3. public void run() {
  4. while (isRunning) {
  5. // do work
  6. }
  7. }
  8. public void kill() {
  9. isRunning = false;
  10. }
  11. }

从上面代码可以看出,这里使用了一个bool变量 isRunning, 通过kill方法,使得isRunning的值变为false, 从而使得while loop停止。我们用volatile修饰 isRunning是保证如果有多个线程使用isRunning值的话,isRunning的值是及时更新的。

转载请注明出处: blog.csdn.net/beiyetengqing

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多