正确处理InterruptException


/**
* interrupt()方法、isInterrupted()方法、interrupted()方法
*/
public class Interrupt {
    public static void main(String[] args) throws Exception {
        Thread t = new Thread(new Worker());
        t.start();

        Thread.sleep(100);
        t.interrupt();

        System.out.println("Main thread stopped.");
    }

    /**
     * 抛出一次InterruptedException异常后JVm会把线程的中断状态清除掉interrupt的状态设置为false
     */
    public static class Worker implements Runnable {
        public void run() {
            System.out.println("Worker started.");

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {

                System.out.println("抛出异常JVM会清除线程的中断状态    Worker IsInterrupted--------: " +
                        Thread.currentThread().isInterrupted());



                // TODO: 2019/1/29 对抛出的InterruptedException的正确处理应该是设置Thread.currentThread().interrupt(); 
                Thread.currentThread().interrupt();
                System.out.println("执行interrupt()设置线程的中断状态 Worker IsInterrupted--------: " +
                        Thread.currentThread().isInterrupted());

                
                /**
                 * 清除线程的中断状态
                 */
                Thread.interrupted();

                System.out.println("清除线程的中断状态interrupted();  Worker IsInterrupted--------: " +
                        Thread.currentThread().isInterrupted());
            }

            System.out.println("Worker stopped.");

        }
    }
}

当线程处于阻塞状态的时候,如果这是被interrupt,会报InterruptException 错误,但是只是设置一个被打断的标志,不会正在的打断状态,所以要正确的处理exception,要加上Thread.currentThread().interrupt()方法,来中断线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值