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

      该方法只是给线程设置了一个停止的标记 并不是真正的立即停止线程

      interrupted() 测试当前线程是否已经中断
      isInterrupted() 测试线程是否已经中断
      停止线程的方法:

    1.异常法 (相当于return出去)
    package entity.thread;
    
    public class Mythread extends Thread{
    
    @Override
    public void run() {
    super.run();
    try {
    for(int i=0;i<500000;i++){
    if(this.interrupted()){
    System.out.println("是停止状态了。。。");
    throw new InterruptedException();
    }
    System.out.println("i=" + (i+1));
    }
    System.out.println("我在for下面");
    } catch (InterruptedException e) {
    System.out.println("进入异常方法了线程终止");
    e.printStackTrace();
    }
    }
    
    
    public static void main(String[] args) throws InterruptedException {
    try {
    Mythread mh = new Mythread();
    mh.start();
    mh.sleep(2000);
    mh.interrupt();
    } catch (Exception e) {
    System.out.println("main catch");
    e.printStackTrace();
    }
    System.out.println("end");
    
    }
    }
    
    打印结果:
    i=223322
    i=223323
    end
    是停止状态了。。。
    进入异常方法了线程终止
    java.lang.InterruptedException
    at entity.thread.Mythread.run(Mythread.java:12)
    
    2.在沉睡中被停止 (程序会直接抛异常)
    package entity.thread;
    
    public class Mythread2 extends Thread{
    
    @Override
    public void run() {
    super.run();
    try {
    System.out.println("run begin");
    Thread.sleep(200000);
    System.out.println("run end");
    } catch (InterruptedException e) {
    System.out.println("在沉睡中被终止! 进入catch!"+ this.isInterrupted());
    e.printStackTrace();
    }
    }
    public static void main(String[] args) {
    try {
    Mythread2 mythread2 = new Mythread2();
    mythread2.start();
    mythread2.sleep(200);
    mythread2.interrupt();
    } catch (InterruptedException e) {
    System.out.println("main catch");
    e.printStackTrace();
    }
    System.out.println("end");
    }
    }
    执行结果
    run begin
    end
    在沉睡中被终止! 进入catch!false
    java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at entity.thread.Mythread2.run(Mythread2.java:10)

    3.暴力停止 stop 方法 已经过时不建议使用并且会存在问题

  • 相关阅读:
    深蓝说区块学习笔记
    Golang语言练习
    WebAssembly学习
    JMeter如何维持登录Session状态
    MySQL脏读、不可重复读、幻读及MVCC
    webrtc源码分析(7)-fec
    webrtc源码分析(9)-拥塞控制(下)-码率分配
    webrtc源码分析(8)-拥塞控制(上)-码率预估
    剑指offer刷题合集
    Visual Studio ------- 将在解决方案中单击文件名,预览文件内容功能开启与关闭
  • 原文地址:https://www.cnblogs.com/ljy-skill/p/10976780.html
Copyright © 2011-2022 走看看