作者byend (漫步)
看板java
标题Re: [问题] Thread interrupt的问题
时间Mon Jul 23 08:06:48 2012
※ 引述《recorriendo (孟新)》之铭言:
: 大家好 小弟最近在学Threading
: 关於interrupt 我查了很多地方都没写得很清楚
: 所以我写了下面这个程式
: public class ThreadPlay extends Thread {
: @Override
: public void run() {
: System.out.println(isInterrupted());
: this.interrupt();
: System.out.println(isInterrupted());
: try {
: Thread.sleep(5000);
: } catch (InterruptedException e) {
: e.printStackTrace();
: }
: System.out.println(isInterrupted());
: }
: public static void main(String[] args) {
: ThreadPlay thr = new ThreadPlay();
: thr.start();
: }
: }
: 执行後 三行println印出来分别是false, true, false
: 所以说 interrupt之後isInterrupted()会传回true
: 但如果有InterruptedException 之後 又会被改回false?
: 请问这是Java原本的设定 还是跟我自己编译器的解读有关? 谢谢各位解答
参考资料: Java Tutorial,
http://tinyurl.com/cbhukxm
摘录最後一段
By convention, any method that exits by throwing an InterruptedException
clears interrupt status when it does so. However, it's always possible
that interrupt status will immediately be set again, by another thread
invoking interrupt.
=>在丢出 InterruptedException之後, Interrupt Status 会被重置为 False..
所以这是Java 语言本身的规定, 你的编译器是如实的执行而已..
虽然 sleep() 函式的运作方式取决於底层 OS, 不过可以这麽理解.
每隔一小段时间, thread 就会起来检查一下, 有没有被 interrupted,
如果有则重置 interrupt status, 接着丢出例外, 交回执行权..
检查的依据就是 interrupt status, 在你的范例中, 已经先呼叫 interrupt
设定 interrupt status = true, 所以 sleep 函式应该是马上中止执行
,重置 interrupt status = false, 并且丢出例外.
以上...
完毕
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 66.235.2.31