我试图理解线程的行为,所以我编写了代码:
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");
}
}
}
输出是:
正在运行
函数
Ex函数
func2
错误
嗨 func2
所以我知道在等待锁定对象被通知时中断线程会抛出IntteruptedException
但是我试图理解线程被中断为什么func 2仍然被正常调用甚至没有异常(exception) ?!!!!
以及为什么即使当前线程已经被中断,Thread.currentThread().isInterrupted()
也会打印false
最佳答案
当你打电话时
t.interrupt();
Thread
t
当前正在执行 wait(1000)
调用。这将导致您捕获
的InterruptedException
。之后,继续正常执行。 func
方法返回并执行 func2
方法。
另外,请阅读 Thread#interrupt()
的 javadoc
If this thread is blocked in an invocation of the
wait()
,wait(long)
, orwait(long, int)
methods of theObject
class, or of thejoin()
,join(long)
,join(long, int)
,sleep(long)
, orsleep(long, int)
, methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
关于java - 中断的线程仍在继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20810570/