Java 关于线程的一些面试题

public boolean isInterrupted() {
    return isInterrupted(false);
}

interrupted是Thread的静态方法

public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}

interrupted 和 isInterrupted类似,只是interrupted会清除标志位
而isInterrupted并不会清除标志位。

比如说下面的调用两次isInterrupted返回结果一样
而调用interrupted先返回true,下一次就返回false

public class Test extends Thread {

    public void run() {
        while (true) {
            if (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread run method");
            } else {
                System.out.println(Thread.currentThread().isInterrupted());
                System.out.println(Thread.currentThread().isInterrupted());
                System.out.println(Thread.interrupted());
                System.out.println(Thread.interrupted());
                return;
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Thread thread = new Test();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

输出下面结果

...
//一直循环输出 Thread run method 省略
Thread run method
Thread run method
Thread run method
true
true
true
false

从上面可以看出两次调用isInterrupted都返回了true
而调用interrupted先返回true,然后清空标志位,下次返回false

疑惑:那interrupted能把false置为true吗?答案是不能

public class Test extends Thread {

    public void run() {
        System.out.println("Thread run method");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().isInterrupted());
            System.out.println(Thread.currentThread().isInterrupted());
            System.out.println(Thread.interrupted());
            System.out.println(Thread.interrupted());
            e.printStackTrace();
            return;
        }
    }

    public static void main(String[] args) throws Exception {
        Thread thread = new Test();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}

这儿输出

Thread run method
false
false
false
false
java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at test.Test.run(Test.java:28)

也就是说interrupted只会把true置为false,不会把false置为true
interrupted只会清除已经中断为true的标志位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值