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的标志位
相关文章推荐
- 一个关于if else容易迷惑的问题
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序