public class WaitNotifyAll {
private static volatile Object resourceA = new Object();
public static void main(String[] args) throws Exception {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
try {
System.out.println("threadA begin wait");
resourceA.wait();
System.out.println("threadA end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread threaB = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("threadC begin notify");
threadA.interrupt();
resourceA.notify();
}
}
});
threadA.start();
Thread.sleep(1000);
threaB.start();
System.out.println("main over");
}
}
这里有两种可能的结果:
抛出中断异常
正常终止
为什么?
我不明白。当threadA被中断时,结果应该抛出InterruptedException。但有时执行这个程序,它可以正常完成。
环境:java8,mac
PIPIONE
森栏
相关分类