您好,欢迎来到年旅网。
搜索
您的当前位置:首页JAVA中线程的终止

JAVA中线程的终止

来源:年旅网

强行终止线程的执行

  • .stop()方法(已弃用)
    这种方式有一个很大的缺点:容易丢失数据,因为直接将进程杀死了,
    线程没有保存的数据会丢失
public class ThreadTest09 {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable3());
        t.setName("t");
        t.start();

        try {
            Thread.sleep(1000 * 5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //5s后杀死进程
        t.stop();  //已弃用
    }
}
class MyRunnable3 implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "————>begin");
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "————>" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + "————>over");
    }
}

合理终止线程的执行

  • 设立一个布尔标记,通过改变标记的方式终止线程
  • 可以在else方法体处进行数据的保存等处理
public class ThreadTest10 {
    public static void main(String[] args) {

        MyRunnable4 run4 = new MyRunnable4();
        Thread t = new Thread(run4);
        t.setName("t");
        t.start();

        try {
            Thread.sleep(1000 * 5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //5s后终止线程
        //想什么时候终止线程,只需把标记改为false即可
        run4.run = false;
    }
}
class MyRunnable4 implements Runnable{
    boolean run = true;  //设立一个布尔标记
    @Override
    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 {
                //在结束之前可以保存
                //save....
                return;
            }
        }
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务