关于notifyAll()的唤醒顺序和程序执行结果,求教了
本帖最后由 cloudeagle_bupt 于 2013-06-06 17:51:35 编辑
package slot;
public class ThreadPriority {
/**
* @param args
*/
public static void main(String[] args) {
Slot s = new Slot();
// TODO Auto-generated method stub
for(int i=1; i<6 ;i++)
{
Consumer cr = new Consumer(s) ;
cr.setPriority(i);
cr.start();
}
Producer p = new Producer(s);
p.start();
}
}
class Slot {
public int slotNum = 0;
public synchronized void produce() {
slotNum++;
}
public synchronized void consume() {
slotNum--;
}
}
class Producer extends Thread {
Slot slot;
public Producer(Slot s) {
slot = s;
}
public void run() {
try {
synchronized (slot) {
while (slot.slotNum == 20)
slot.wait();
slot.produce();
slot.notifyAll();
System.out.println("Thread " + this.getName() + " producing ! slotNum is " + slot.slotNum+"\n");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Consumer extends Thread {
Slot slot;
public Consumer(Slot s) {
slot = s;
}
public void run() {
try {
synchronized (slot) {
while (slot.slotNum == 0)
slot.wait();
slot.consume();
slot.notifyAll();
System.out.println(" -------------- Thread " + this.getName() + " consuming ! slotNum is " + slot.slotNum+"\n");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
分享到:
[解决办法]
这个程序没有错,main方法先它运行5个线程,由于slot.slotNum == 0,均等待,直到
Producer p = new Producer(s);
p.start(); 运行
synchronized (slot) { while (slot.slotNum == 20) slot.wait(); slot.produce(); slot.notifyAll(); System.out.println("Thread " + this.getName() + " producing ! slotNum is " + slot.slotNum+"\n"); }
slot.produce(); 这儿slot.slotNum == 1,
slot.notifyAll唤醒所有线程,
打印System.out.println("Thread " + this.getName() + " producing ! slotNum is " + slot.slotNum+"\n");该 线程结束,
其中thread4抢到资源,线程4运行完slot.slotNum == 0,其他线程继续等待
最终原因你只生参了一个产品,消费共有五个线程,一个运行晚还有4个。自然是等待
[解决办法]
不建议用优先级。因为有些语言不支持1到10的。notify是随机唤醒的,要想唤醒特定的线程,设置相应的bool值变量。