Java如何安全终止一个线程:(提供两种方式参考)

Thread类提供了一个线程终止的方法stop()方法,但是现在在JDK源码中发现,stop()方法已经被废弃。主要原因是:stop()方法强制终止一个正在执行的线程,可能会造成数据不一致的问题。

所以常用的线程终止有两种方式:

1.使用标志位退出线程

2.使用interrupt终止线程(注意: 单独调用Interrupt()并不会终止线程, 需要使用Thread.isInterrupted()判断线程是否被中断,然后进入中断处理逻辑代码)

1. 使用标志位退出线程

这种也是最常用的方法,就是定义一个boolean型的标志位,在线程的run方法中根据这个标志位是true还是false来判断是否退出,这种情况一般是将任务放在run方法中的一个while循环中执行的。

public class StopThread {
    public static void main(String[] args) throws InterruptedException {
        StopRunner runnable = new StopRunner();
        Thread thread = new Thread(runnable);
        thread.start();
        Thread.sleep(2);
        runnable.cancel();
    }

    private static class StopRunner implements Runnable {
        private long i;
        private volatile boolean disableCancel = true;// 1

        @Override
        public void run() {
            while (disableCancel) {
                i++;
                System.out.println("i=" + i);
            }
            System.out.println("stop");
        }

        public void cancel() {
            disableCancel = false;
        }
    }
}

运行结果:

i=1
i=2
i=3
...
...
...
i=111
i=112
i=113
stop

2.使用interrupt终止线程

/**
 * 单独调用Interrupted并不会终止线程
 *
 */
public class InterruptedDemo {
	 public static void main(String[] args) {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("The thread is waiting for interrupted!");
                    // 中断处理逻辑
                    if (Thread.currentThread().isInterrupted()) {
                        System.out.println("The thread 0 is interrupted!");
                        break;
                    }
                }
            }
        };
        t1.start();
        t1.interrupt();// 中断线程
        System.out.println("The thread is interrupted!");
    }
}

运行结果:

The thread is interrupted!
The thread is waiting for interrupted!
The thread 0 is interrupted!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值