【发布时间】:2017-05-19 18:13:32
【问题描述】:
在下面的语句中,wait() 方法被执行,即使没有调用 notify,但语句 below wait() 仅在 laurel 线程完成执行后执行。
我尝试使用其他对象来锁定 hardy 块的同步,这次等待方法仍然永远等待,谁能解释我为什么执行wait() 之后的语句?
package delagation;
public class Solution extends Thread {
static Thread laurel, hardy;
public static void main(String[] args) throws InterruptedException {
laurel = new Thread() {
public void run() {
System.out.println("A");
try {
hardy.sleep(1000);
} catch (Exception e) {
System.out.println("B");
}
System.out.println("C");
}
};
hardy = new Thread() {
public void run() {
System.out.println("D");
try {
synchronized(laurel) {
laurel.wait();
//wait method is called here,
//There is not notify in this class,
//but the statement below are executing
System.out.println(Thread.currentThread().getName());
}
} catch (Exception e) {
System.out.println("E");
}
System.out.println("F");
}
};
laurel.setName("laurel");
hardy.setName("hardy");
laurel.start();
hardy.start();
}
}
【问题讨论】:
-
你希望这段代码能做什么?!当
Thread死亡时,它会调用notifyAll。从不extends Thread。永远不要在Thread上使用synchronized。除非你真的知道你在做什么...... -
@BoristheSpider 千万不要练习,请打他的脸!
-
我知道有这个副本,但我找不到。
-
鲍里斯的所有cmets都在现场。他在三行 cmets 中给出了很多有用的反馈。我真的不明白这如何转化为打脸。
标签: java multithreading synchronized java-threads