You*_*ans 0 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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
运行
FUNC
Ex func
FUNC2
假
嗨func2
所以我知道在等待锁定对象被通知时中断线程会抛出IntteruptedException但是我正在试图理解线程被中断为什么func 2仍然被正常调用而没有异常?!!!! 以及为什么Thread.currentThread().isInterrupted()打印false即使当前线程已经被中断
你打电话的时候
t.interrupt();
Run Code Online (Sandbox Code Playgroud)
在Thread t当前正在执行的wait(1000)调用.这将导致InterruptedException你catch.之后,执行继续正常进行.该func方法返回并func2执行该方法.
另外,阅读javadoc Thread#interrupt()
如果该线程阻塞的调用
wait(),wait(long)或wait(long, int)该方法的Object类,或的join(),join(long),join(long, int),sleep(long),或者sleep(long, int),这个类的方法,那么它的中断状态将被清除,它还将收到一个InterruptedException.