java停止线程

停止线程

停止线程需要一定的技巧。需要做好防范措施,避免“线程不安全”。

  1. 使用Thread.interrupt()

使用interrupt停止线程

原理

对线程队形调用interrupt()方法,这个方法仅仅是给线程打一个停止状态的标记,并不会真正停止。

可以通过条件判断检验这个标记后,主动抛出异常并停止线程或后直接return,可以称之为异常法和return法。

判断interrupt标志:

Thread.java提供了两种方法。

  1. 静态方法Thread.interrupted()
  2. 线程对象的方法example.isInterrupted(),example是线程实例。

两者区别:两者都可以判断是否处于停止状态(或者说是否含有interrulted标志,更容易理解),但是Thread.interrupted()还具有清除状态标志的功能。

假设线程a 被打入了interrupted标志,那么如果连续调用两次example.isInterrupted(),返回的是true,true

而连续两次调用Thread.interrupted(),返回的则是true、false,这是因为第二次调用Thread.interrupted()的时候,interrupted状态已经被第一次重置了。

A、抛出异常法

(1)运行状态下打入interrupted标志

继承Thread创建MyThread3,遇见interrupted标志后主动抛出InterruptedException。

package foreverly.cn.chapter1;

public class MyThread3 extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 5000; i++) {
//					检测是否含有interrupted标志
                if (this.isInterrupted()) {
                    System.out.println("打入了interrupted标志");
                    System.out.println("这只是个标志,并不会直接停止运行");
//                抛出异常法
                    throw new InterruptedException();
                }
                System.out.println("i=" + i);
            }
//			验证线程确实终止            
            System.out.println("我在for下面,不会被执行");
        } catch (InterruptedException e) {
            System.out.println("主动抛出的异常被抓住了");
            e.printStackTrace();
        }
    }
}

测试Test3.java

package foreverly.cn.chapter1;

public class Test3 {
    public static void main(String[] args) {
        try {
            MyThread3 thread = new MyThread3();
            thread.start();
            Thread.sleep(10);
            thread.interrupt();
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("进入main线程的catch,作用于Thread.sleep(2000)");
            e.printStackTrace();
        }
        System.out.println("main线程结束");
    }
}

输出结果:

i=1
i=2
......
i=193
i=194
i=195
打入了interrupted标志
这只是个标志,并不会直接停止运行
主动抛出的异常被抓住了
java.lang.InterruptedException
	at foreverly.cn.chapter1.MyThread3.run(MyThread3.java:13)
main线程结束

for循环到i=195的时候被打入了interrupted标志,通过 if (this.isInterrupted())判断含有interrupted标志,于是throw new InterruptedException()主动抛出异常并捕获,实现了线程的终止。

当sleep与遇上了interrupted

上面讨论的是运行状态下的线程通过interrupted标志。如果sleep状态的线程被打上interrupted 标记时,或者被interrupted标志的线程调用sleep,会发生什么呢?

(1)先sleep后被打上interrupted标志

package foreverly.cn.chapter1;

public class MyThread2 extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("run begin");
//           让此线程sleep足够时间
            Thread.sleep(200000000);
            System.out.println("这里不会执行");
        } catch (InterruptedException e) {
            System.out.println("在sleep中进入catch");
            e.printStackTrace();
        }
    }

}

package foreverly.cn.chapter1;

public class TestMain2 {
   public static void main(String[]  args) {
      MyThread2 thread = new MyThread2();
      thread.start();
//    让主线程sleep一段时间,保证thread线程可以进入sleep状态。
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      thread.interrupt();
      System.out.println("main end");
      
   }

}
run begin
main end
在sleep中进入catch
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at foreverly.cn.chapter1.MyThread2.run(MyThread2.java:9)

注意,这里的异常并非主动抛出,说明当sleep状态的线程被打入interrupted时,会立即抛出java.lang.InterruptedException:sleep interrupted

(2)先打上interrupted标记后进入sleep

package foreverly.cn.chapter1;

public class MyThread2 extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            System.out.println("run begin");
           while (true) {
               if (this.isInterrupted()){
                   System.out.println("thread线程被打入interrupted标志");
                   break;
               }
               System.out.println("thread运行中...");
           }
            Thread.sleep(20000);
            System.out.println("run end");
        } catch (InterruptedException e) {
            System.out.println("先interrupt,在遇到sleep,进入catch");
            e.printStackTrace();
        }
    }

}
package foreverly.cn.chapter1;

public class TestMain2 {
   public static void main(String[]  args) {
      MyThread2 thread = new MyThread2();
      thread.start();
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      thread.interrupt();
      System.out.println("main end");
      
   }

}

输出:

thread运行中...
thread运行中...
thread运行中...
thread运行中...
thread运行中...
......
thread运行中...
thread运行中...
thread运行中...
thread运行中...
thread运行中...
thread线程被打入interrupted标志
main end
先interrupt,在遇到sleep,进入catch
java.lang.InterruptedException: sleep interrupted
	at java.lang.Thread.sleep(Native Method)
	at foreverly.cn.chapter1.MyThread2.run(MyThread2.java:16)

综上可知:会立即抛出java.lang.InterruptedException: sleep interrupted

B、return法

将上述抛出异常并捕获,改为直接return。

更推荐使用异常法,抛出异常可以实现程序的分流,更好的控制程序,而过多的return会污染程序。

C、stop暴力停止

这个方法太暴力了,所以被废弃了。

当对一个线程对象调用stop方法时,线程会立刻停止。(并且会抛出java.lang.ThreadDeath异常,但通常此异常不需要显示捕捉。)

说其暴力,是因为调用后立刻停止,很容易造成数据不同步。

举个例子,线程a的run方法用来改变用户名和密码,并未为了保证线程安全,避免同步修改使用了synchronized。可是,当线程运行时,改变了用户名,此时CPU资源切换到线程b,线程b中通过a.stop()把线程a暴力停止了,那么线程a只修改了用户名,却没修改密码。

所以stop被废弃。

posted @ 2019-06-01 19:08  落音  阅读(795)  评论(0编辑  收藏  举报