Thread.currentThread().interrupt()和Thread.interrupted()和Thread.currentThread().isInterrupted()

Thread.interrupted() 可以返回当前标志位并使标志位为false
Thread.currentThread().interrupt() 可以使标志位置为true
Thread.currentThread().isInterrupted() 返回当前线程标志位

如果线程中使用了sleep,wait,当调用thread.interrupt()的时候,会使当前线程中断标志位值为false,
并触发异常InterruptedException

public static void main(String[] args) {

        AtomicInteger atomicInteger = new AtomicInteger(0);

        Thread thread = new Thread(() -> {
            for (; ; ) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    System.out.println("InterruptedException   "+Thread.currentThread().isInterrupted());
                    boolean interrupted = Thread.interrupted();
                    System.out.println("interrupted===="+interrupted);
                }
                int i = atomicInteger.incrementAndGet();
                if (i==2){
                    Thread.currentThread().interrupt();
//                    boolean interrupted = Thread.interrupted();
//                    System.out.println("interrupted===="+interrupted);
                }
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Thread.currentThread().isInterrupted() "+Thread.currentThread().isInterrupted());
                    if (i==80000){
                      boolean interrupted = Thread.interrupted();
                      System.out.println("interrupted===="+interrupted);
                    }
//                    boolean interrupted = Thread.interrupted();
//                    System.out.println("interrupted===="+interrupted);

                }
                System.out.println(Thread.currentThread().isInterrupted());

//                if (Thread.currentThread().isInterrupted()) {
//                    System.out.println(Thread.currentThread().isInterrupted());
//                }
            }
        });
        thread.start();
//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        System.out.println("Interrupted");
//        Thread.interrupted();
//        thread.interrupt();
//        thread.in
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值