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

    1.5 线程停止

    结束线程有以下三种方法:

    (1)设置退出标志,使线程正常退出。

    (2)使用interrupt()方法中断线程。

    (3)使用stop方法强行终止线程(不推荐使用Thread.stop, 这种终止线程运行的方法已经被废弃,使用它们是极端不安全的!)

    public class Demo8Exit {
    ​
        public static boolean exit = true;
    ​
        public static void main(String[] args) throws InterruptedException {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    while (exit) {
                        try {
                            System.out.println("线程执行!");
                            Thread.sleep(100l);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            t.start();
    ​
            Thread.sleep(1000l);
            exit = false;
            System.out.println("退出标识位设置成功");
        }
    }

    public class Demo9Interrupt {
    
        public static boolean exit = true;
    
        public static void main(String[] args) throws InterruptedException {
            Thread t = new Thread(new Runnable() {
                public void run() {
                    while (exit) {
                        try {
                            System.out.println("线程执行!");
    
                            //判断线程的中断标志来退出循环
                            if (Thread.currentThread().isInterrupted()) {
                                break;
                            }
    
                            Thread.sleep(100l);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            //线程处于阻塞状态,当调用线程的interrupt()方法时,
                            //会抛出InterruptException异常,跳出循环
                            break;
                        }
                    }
                }
            });
            t.start();
    
            Thread.sleep(1000l);
            //中断线程
            t.interrupt();
            System.out.println("线程中断了");
        }
    }
  • 相关阅读:
    python基础(三)python数据类型
    python基础(二)条件判断、循环、格式化输出
    postman测试上传文件
    postman添加权限验证
    postman添加cookie
    postman发送json格式的post请求
    postman发送post请求
    如果json中的key需要首字母大写怎么解决?
    fastjson转jackson
    git初识
  • 原文地址:https://www.cnblogs.com/angdh/p/15565337.html
Copyright © 2011-2022 走看看