您的位置:首页 > 职场人生

Java 关于线程的一些面试题

2016-04-02 22:51 489 查看
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的标志位
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息