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;
                }
            }
        }
    }
  • 相关阅读:
    环境变量设置set env exportFedora Centos日志我的搜狐
    Hadoop Streaming 编程
    业务开发测试HBase之旅三:通过Java Api与HBase交互
    hadoop+zookeeper+hbase安装_dekar_x的空间_百度空间
    HBase Java客户端编程
    Hadoop应用测试
    HBase vs Cassandra: 我们迁移系统的原因
    关于HBase的一些零碎事
    奔流 | 自由、奔放的技术刊物
    Paxos在大型系统中常见的应用场景
  • 原文地址:https://www.cnblogs.com/peiminer/p/13613835.html
Copyright © 2011-2022 走看看