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;
                }
            }
        }
    }
  • 相关阅读:
    阿杜复博通知
    vim 配置文件 ,高亮+自动缩进+行号+折叠+优化
    网络课设总结(五)——利用CAsyncSocket进行异步通信
    网络课设总结(四)——利用CAsyncSocket进行异步通信
    网络课设总结(三)——VC++应用技巧
    ubuntu11.10下配置adsl上网
    反省
    cp命令“d”参数解释及实例
    网络课设总结(二)——VC开发环境
    SharePoint中如何获得当前用户的loginName
  • 原文地址:https://www.cnblogs.com/peiminer/p/13613835.html
Copyright © 2011-2022 走看看