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("线程中断了");
        }
    }
  • 相关阅读:
    ACCP7.0-S2-复习自测-15测试分析
    线程
    多线程下的单例模式
    combobox 属性、事件、方法
    java的多线程总结
    爬虫--登录网页
    shell--字符串是否为空
    python--正则表达式 字符串匹配
    mysql---表所在数据库
    python--日期操作
  • 原文地址:https://www.cnblogs.com/angdh/p/15565337.html
Copyright © 2011-2022 走看看