Java 关于线程的一些面试题

来源:互联网 发布:电子商务的软件流程图 编辑:程序博客网 时间:2024/05/16 14:11
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 methodThread run methodThread run methodtruetruetruefalse

从上面可以看出两次调用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 methodfalsefalsefalsefalsejava.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的标志位

0 0
原创粉丝点击