gpt4 book ai didi

java - 中断的线程仍在继续执行

转载 作者:行者123 更新时间:2023-12-01 07:28:16 24 4
gpt4 key购买 nike

我试图理解线程的行为,所以我编写了代码:

    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), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com