zoukankan      html  css  js  c++  java
  • 1.7.1停止不了的线程

    调用interrupt()来停止线程,但是interrupt()方法的使用效果并不像是for+break语句那样,马上就停止循环,调用此方法仅仅是在当前线程中打了一个停止的标记,并不是真正的停止线程。

    测试如下

     1 package com.cky.thread;
     2 
     3 /**
     4  * Created by edison on 2017/11/28.
     5  */
     6 public class MyThread11 extends  Thread{
     7     @Override
     8     public void run() {
     9         super.run();
    10         for (int i = 0; i < 50000; i++) {
    11             System.out.println("i="+i);
    12         }
    13     }
    14 }
     1 package com.cky.test;
     2 
     3 import com.cky.thread.MyThread11;
     4 
     5 /**
     6  * Created by edison on 2017/11/28.
     7  */
     8 public class Test18 {
     9     public static void main(String[] args) {
    10         try {
    11             MyThread11 th = new MyThread11();
    12             th.start();
    13             Thread.sleep(2000);
    14             th.interrupt();
    15 //            System.out.println("是否停止1="+ th.isInterrupted());
    16 //            System.out.println("是否停止2="+ th.isInterrupted());
    17         } catch (InterruptedException e) {
    18             e.printStackTrace();
    19         }
    20     }
    21 }
    i=49988
    i=49989
    i=49990
    i=49991
    i=49992
    i=49993
    i=49994
    i=49995
    i=49996
    i=49997
    i=49998
    i=49999
    
    Process finished with exit code 0

    结果分析:

    主函数开始执行的是主线程,当执行语句sleep时,切换到了子线程,这时执行i++方法打印,之后主线程休眠结束,执行interrupt方法,但是子线程还是在执行i++方法,直到循环结束,线程停止。

    说明interrupt方法并不能停止线程。

  • 相关阅读:
    form表单
    JsonResponse对象
    HttpRequest对象
    Django基础
    ssh私钥登录
    监控window目录是否为空自定义item
    redis频繁报错Cannot allocate memory
    脱敏html文件文件
    MySQL删除数据
    ftp服务器搭建
  • 原文地址:https://www.cnblogs.com/edison20161121/p/7954735.html
Copyright © 2011-2022 走看看