我有以下代码:
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
ThreadImpl thr = new ThreadImpl();
thr.start();
Thread.sleep(1000);
synchronized(thr){
System.out.println( "MAIN "+thr.hashCode());
System.out.println("Main -->got the lock");
thr.wait();
System.out.println("Main -->Done with waiting");
}
}
}
class ThreadImpl extends Thread{
public synchronized void sayHello(){
System.out.println("Ssay hello ");
}
@Override
public void run() {
synchronized(this){
System.out.println( "METHOD "+this.hashCode());
System.out.println("METHOD Got the lock ");
System.out.println("METHOD Going for sleep ");
for(int i =0;i< 100000;i++);
try {
Thread.sleep(2000);
System.out.println("METHOD Woke up ");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("METHOD Done leaving the thread");
}
}
}在ThreadDemo的main方法中,我创建了一个线程对象ThreadImpl并启动它。接下来,主线程休眠1000ms。线程的run方法将在一个单独的thread.As部分中执行,它循环100000次,休眠2000ms。然后它退出该方法。主线程唤醒并获取"thr“的锁,然后进入等待状态。因为另一个线程已经完成了它的执行,这个等待应该是永远的。然而,我看到了以下结果:
方法1729414014
方法获得了锁
进入睡眠状态的方法
方法被唤醒
方法已完成离开线程
MAIN 1729414014
Main -->获得锁
Main -->等待完成
当没有人通知main方法时,它是如何继续执行的呢?
发布于 2018-03-29 22:02:36
这是虚假唤醒,请参阅jls
由于以下任何一种操作,线程可能会从等待集中删除,并将在稍后的某个时间恢复:
的情况下恢复
https://stackoverflow.com/questions/49549773
复制相似问题