zoukankan      html  css  js  c++  java
  • java之终止多线程的方法

    先看一段代码:

    这是第一种方式,利用stop()方法强行终止一个线程。这种方式存在很大的缺点,容易数据丢失,因为这种方式是直接将线程杀死,线程没有保存的数据将会丢失,不建议使用。

    public class ThreadTest07 {
        public static void main(String[] args) throws InterruptedException {
    
            Thread t = new Thread(new MyRunnable7());
            t.setName("t");
            t.start();
    
            Thread.sleep(1000 * 5);
    
            //5s之后强行终止t线程
            t.stop();  //已经过时,不建议使用
    
            /**这种方式存在很大的缺点,容易数据丢失,因为这种方式是直接将线程杀死,线程没有保存的数据将会丢失
             *
             * */
        }
    }
    
    class MyRunnable7 implements Runnable{
    
        public void run() {
            for (int i = 0;i<10; i++){
    
                System.out.println(Thread.currentThread().getName() + "---" + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    如何合理的终止一个线程?

    //打一个布尔标记,判断要不要进行下去。
        boolean run = true;
    public class ThreadTest08 {
        public static void main(String[] args) throws InterruptedException {
    
            MyRunnable8 r = new MyRunnable8();
            Thread t = new Thread(r);
            t.setName("t");
            t.start();
    
            //模拟5s
            Thread.sleep(1000 * 5);
    
            //想什么时候结束,改变条件就好
            r.run = false;
        }
    }
    
    class MyRunnable8 implements Runnable{
    
        //打一个布尔标记
        boolean run = true;
    
        public void run() {
            for (int i = 0;i<10; i++){
    
                if(run){
                    System.out.println(Thread.currentThread().getName() + "---" + i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    //return结束,在结束前还有什么没保存的,这里可以保存
                    //save
    
                    //终止当前线程
                    return;
                }
            }
        }
    }
  • 相关阅读:
    Linux学习笔记8——VIM编辑器的使用
    Linux学习笔记7——linux中的静态库和动态库
    Linux学习笔记6——映射虚拟内存
    Linux学习笔记5——虚拟内存
    Linux学习笔记4——函数调用栈空间的分配与释放
    C++中new和malloc
    Linux学习笔记3——Linux中常用系统管理命令
    Linux学习笔记2——Linux中常用文件目录操作命令
    python的基本语法
    11.3 自定义注解
  • 原文地址:https://www.cnblogs.com/peiminer/p/13613835.html
Copyright © 2011-2022 走看看