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;
            }
        }
    }
}

 

posted @ 2020-09-04 14:50  裴敏儿  阅读(417)  评论(0编辑  收藏  举报