zoukankan      html  css  js  c++  java
  • Java多线程(五)停止线程 interrupt

    调用interrupt方法仅仅是在当前线程中打了一个停止的标记,并不是真正停止线程。

    this.interrupted() :测试当前线程是否已经中断,执行后具有将状态标志清除为false的功能

    isInterrupted() :   测试线程Thread对象是否已经是中断状态,但不清除状态标志。

    public class InterruptDemo extends Thread{
    
        public void run(){
            super.run();
            try{
                
            for(int i =0;i< 500000;i++){
                if(this.isInterrupted()){
                    System.out.println("run:" +InterruptDemo.interrupted());
                    System.out.println("已经是停止状态了!");
                    //throw new InterruptedException(); 代替break 解决 后面语句继续执行的问题, 即:System.out.println("我在for的下面,线程终止了");
    //                break;
                    throw new InterruptedException();
                }
                System.out.println("i="+(i+1));
            }
            System.out.println("我在for的下面,线程终止了");
            }catch(Exception e){
                System.out.println("进入run方法中的catch了!!");
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
    
            try {
                InterruptDemo thread = new InterruptDemo();
                thread.start();
                Thread.sleep(2000);
                thread.interrupt();
                System.out.println("thread"+thread.isInterrupted());
                System.out.println("main:"+InterruptDemo.interrupted());
                
                //Thread.currentThread().interrupt();
                //System.out.println(Thread.interrupted());
                ///System.out.println(Thread.interrupted());
                
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    Mysql权限控制
    Linux查看端口
    linus 下redis守护进程启动
    pymongo创建索引
    mongo批量操作存在更新否则插入
    梯度下降推导过程资料整理
    [转]mitmproxy套件使用攻略及定制化开发
    终极利器!利用appium和mitmproxy登录获取cookies
    how-to-pass-a-class-variable-to-a-decorator-inside-class-definition
    python进阶之魔法函数
  • 原文地址:https://www.cnblogs.com/newlangwen/p/7595249.html
Copyright © 2011-2022 走看看