十五 停止线程

1: Interrup:

直接上代码:

package multyThread;

public class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        try {
            for (int i = 0; i < 500000; i++) {
                if (this.isInterrupted()) {
                    System.out.println("停止状态");
                    throw new InterruptedException();
                }
                System.out.println("i=" + (i + 1));
            }
        } catch (InterruptedException e) {
            System.out.println("异常");
        }
    }
}
package multyThread;

public class Test {
    public static void main(String[] args) {
        try {
            MyThread thread = new MyThread();
            thread.start();
            Thread.sleep(100);
            thread.interrupt();

            System.out.println(thread.interrupted());   # 这个判断的是当前线程(看源码就知道了)

            System.out.println(thread.isInterrupted()); # 这个是判断thread线程的状态,所以是true
            System.out.println(thread.isInterrupted()); # 不清除标志。这个是判断thread线程的状态,所以是true
 } catch (InterruptedException e) { e.printStackTrace(); } } }

result: 

         

i=256
i=257
true
true
停止状态
异常
异常退出

2:stop:已经不建议使用

  使用stop() 停止的线程则是非常暴力的。

       stop() 已经废弃了,因为:

    1 如果强制停止则有可能使得一些清理工作得不到完成。

    2 对锁定的对象进行了“解锁”,导致数据得不到同步的处理,出现数据不一致。

     (比如run方法调用了一个同步的方法,在同步方法执行一半的时候,stop()调用了,导致

      这个同步方法执行一半后结束,同时锁也释放了。而这个同步方法只执行一半,就可能导致

      数据不一致的情况发生。)

3: 设置一个volatile变量作为标志位,多线程情况下,去check.

原文地址:https://www.cnblogs.com/liufei1983/p/9849906.html