中断的线程仍在继续执行

时间:2013-12-28 03:02:54

标签: java multithreading

我正在尝试理解线程的行为,所以我做了代码的和平:

    public class Threads extends Thread {
        private Account account = new Account();
        public static void main(String[] args) {
            Threads t = new Threads();
            t.start();
            t.interrupt();
        }
   @Override
    synchronized public void run() {
        System.out.println("Running...");
        account.func();account.func2();
    }

}
class Account {

    public synchronized void func()  {
        try {
            System.out.println("func");
            wait(1000);
            System.out.println("hi func");
        } catch (InterruptedException ex) {
            System.out.println("Ex func");
        }
    }
    public synchronized void func2()  {
        try {
            System.out.println("func2");
           wait(2000);
            System.out.println(Thread.currentThread().isInterrupted());
            System.out.println("Hi func2");
        } catch (InterruptedException ex) {
            System.out.println("Ex func2");
        }
    }
}
输出是:

运行

FUNC

Ex func

FUNC2

你好func2

所以我知道在等待锁定对象被通知时中断线程会抛出IntteruptedException但是我试图理解线程被中断为什么func 2仍然被正常调用而没有异常?! ! 以及为什么Thread.currentThread().isInterrupted()打印false即使当前线程已经被中断

1 个答案:

答案 0 :(得分:7)

致电时

t.interrupt();

Thread t当前正在执行wait(1000)来电。这将导致您InterruptedException的{​​{1}}。之后,执行继续正常进行。 catch方法返回并执行func方法。

另外,请阅读Thread#interrupt()

的javadoc
  

如果在func2wait()的调用中阻止此线程,   或wait(long)类或wait(long, int)的{​​{1}}方法,   Objectjoin()join(long)join(long, int)方法   在这个类中,然后它的中断状态将被清除   收到InterruptedException。

相关问题