三、线程的中断方式

自然结束

要么是run执行完成了,要么是抛出了一个未处理的异常导致线程提前结束。


API方式

  • suspend(): 挂起线程
  • resume(): 激活线程
  • stop(): 中断线程

但是这些API是过期的,也就是不建议使用的。

不建议使用的原因主要有:以suspend()方法为例,在调用后,线程不会释放已经占有的资源(比如锁),而是占有着资源进入睡眠状态,这样容易引发死锁问题。

同样,stop()方法在终结一个线程时不会保证线程的资源正常释放,通常是没有给予线程完成资源释放工作的机会,因此会导致程序可能工作在不确定状态下。

正因为suspend()、resume()和stop()方法带来的副作用,这些方法才被标注为不建议使用的过期方法。


通知中断

interrupt()

通知线程中断

    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        Thread thread = new Thread(() -> {
            Thread ct = Thread.currentThread();
            while (!ct.isInterrupted()) {
            }
            System.out.println(ct.getName()+"被中断了");
        });
        thread.start();
        System.out.println("输入任意键中断");
        System.in.read();
        thread.interrupt();
    }

isInterrupted()

判断线程是否被中断

    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
            }
            System.out.println("中断了");
        });
        thread.start();
        System.out.println("输入任意键中断线程");
        System.in.read();
        thread.interrupt();
    }

Thread#interrupted()

测试是否中断线程,如果当前线程是中断状态,会清除当前线程的中断标志,重新让当前线程状态为正常状态。

    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
            }
            System.out.println("第一次状态:"+Thread.interrupted());
            System.out.println("第二次状态:"+Thread.interrupted());
        });
        thread.start();
        System.out.println("输入任意键查看线程状态");
        System.in.read();
        thread.interrupt();
    }
}


  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值