【发布时间】:2013-12-03 06:08:36
【问题描述】:
驱动程序.java
public class Driver {
static Object obj = new Object();
public static void main(String [] args) throws InterruptedException
{
Thread thr = new Thread(new Runnable(){
@Override
public void run() {
System.out.println("Thread 1: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 1: Completed processing.");
System.out.println("Thread 1: Notifying other waiting threads.");
obj.notify();
}
}
});
Thread thr2 = new Thread(new Runnable(){
@Override
public void run() {
System.out.println("Thread 2: Waiting for available slot.");
synchronized(obj){
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Found slot!");
long x = 0;
while(x < Integer.MAX_VALUE) x++;
System.out.println("Thread 2: Completed processing.");
System.out.println("Thread 2: Notifying other waiting threads.");
obj.notify();
}
}
});
thr.start();
thr2.start();
System.out.println("Main Thread: All processing units busy.");
// Thread.sleep(2000); // Enable this and disable the other Thread.sleep(...) and NOW we are good. But again, 'why?' is the question.
synchronized(obj){
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
System.out.println("Main Thread: Found ONLY 1 available slot.");
obj.notify();
obj.wait(); // JVM should catch this as the last request so it has the least priority.
System.out.println("Main Thread: Finished and exiting...");
}
}
}
上面的代码不会notifyThreads,因为下面这行:
Thread.sleep(2000); // This causes a failure. Move it outside the synchronized and it will work why?
请结合整个班级的背景来看看这句话。如果将该行放在Main Thread 的synchronized 块内,我很难确定这个简单的概念验证会失败的原因。
谢谢
【问题讨论】:
-
我认为这是一条红鲱鱼。我怀疑问题是其中一个子线程首先进入关键块(在
obj上同步),因此父线程从不 到达obj.notify孩子的@ 987654329@(同样,如果父母先进入,信号将在孩子等待它之前出现)。 -
对我来说,进入临界区然后休眠 20 秒没有多大意义。你永远不会在实时操作系统中这样做,因为如果低优先级任务首先进入临界区,然后决定通过睡觉来浪费每个人的时间,这会导致优先级倒置。
-
你为什么要使用这样的
static互斥锁?您正在等待、通知和同步一个 obj。 -
是的,我知道。我试图弄清楚当
synchronizing时,您实际上可以通过调用wait来删除lock标志,并允许其他synchronized块继续处理object,然后notify其他@987654337 @ 块lock标志已被禁用。 -
@user2864740 我明白你现在的意思了。这很有意义!你为什么不把它作为答案,至少我可以把它标记为正确的答案。
标签: java multithreading wait notify