关于线程Thread中断

    public static void main(String[] args) throws Exception {
        Thread test = new Thread(() -> {
            try {
                System.out.println("stateName4:" + Thread.currentThread().getState().name()); // RUNNABLE
                int count = 0;
                while (true) {
//                    if (count++ > 10000) {
//                        System.out.println("success to 10000");
//                        break;
//                    }
                    Thread.sleep(10000);
                }
            } catch (Exception e) {
                if (e instanceof InterruptedException) {
                    // false 当线程调用sleep(),wait(),join()等方法而阻塞,在被打断时会抛出InterruptedException异常,并且打断状态被重置reset
                    System.out.println("state1: " + Thread.currentThread().isInterrupted());

                    // Just to set the interrupt flag (set true)
                    Thread.currentThread().interrupt();
                    System.out.println("state2: " + Thread.currentThread().isInterrupted()); // true

                    // return thread interrupt status and then clearInterrupt (set false)
                    System.out.println("state3: " + Thread.interrupted());
                    System.out.println("state4: " + Thread.currentThread().isInterrupted()); // false

                    System.out.println("stateName5:" + Thread.currentThread().getState().name()); // RUNNABLE
                }
            } finally {
                System.out.println(Thread.currentThread().getName() + "" + (Thread.currentThread().isInterrupted() ? " is interrupted!" : " is not interrupted!"));
                System.out.println("stateName6:" + Thread.currentThread().getState().name()); // RUNNABLE
            }
        });

        // 启动线程
        test.start();
        System.out.println("stateName1:" + test.getState().name()); // RUNNABLE

        // 主线程让出cpu
        Thread.sleep(1000);
        System.out.println("stateName2:" + test.getState().name()); // TIMED_WAITING

        // 打断线程
        test.interrupt();
        System.out.println(test.isInterrupted()); // true

        Thread.sleep(1000);
        System.out.println("stateName3:" + test.getState().name()); // TERMINATED
    }

转载于:https://my.oschina.net/u/2375016/blog/856903

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值