首页 > 编程语言 > 详细

java之终止多线程的方法

时间:2020-09-04 15:19:41      阅读:41      评论:0      收藏:0      [点我收藏+]

先看一段代码:

这是第一种方式,利用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;
            }
        }
    }
}

 

java之终止多线程的方法

原文:https://www.cnblogs.com/peiminer/p/13613835.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!