zoukankan      html  css  js  c++  java
  • 十五 停止线程

    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.

  • 相关阅读:
    Different ways how to escape an XML string in C#
    __VIEWSTATE
    Git for Computer Scientists
    关于SQL Server死锁
    20个开源项目托管站点
    Understanding Host Headers in IIS
    开发与研发:区别很大
    Linux 0.12 “轮子”任务调度图示
    RabbitMQ学习第二记:工作队列的两种分发方式,轮询分发(Roundrobin)和 公平分发(Fair dispatch)
    ResultSetMetaData中getColumnLabel和getColumnName的区别
  • 原文地址:https://www.cnblogs.com/liufei1983/p/9849906.html
Copyright © 2011-2022 走看看