以下生产者-消费者代码显示错误的订单(在生产者生产-消费者消费之前。有时生产者生产多个项目(小隔间只允许一个项目(。为什么?
public class CubbyHole {
private int content;
private boolean available=false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) {}
}
available = false;
notify();
return content;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
} catch (InterruptedException e) { }
}
content = value;
available = true;
notifyAll();
}
}
public class Consumer extends Thread {
CubbyHole c;
public Consumer(CubbyHole c){
this.c=c;
}
public void run(){
int val=0;
for(int i =0;i<10;i++){
val=c.get();
System.out.println("consumer gets "+val);
}
}
}
public class Producer extends Thread {
CubbyHole c;
public Producer(CubbyHole c){
this.c=c;
}
public void run(){
for(int i=0;i<10;i++){
c.put(i);
System.out.println("Producer puts "+i);
}
}
}
public class Dimo {
public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p = new Producer(c);
Consumer con = new Consumer(c);
p.start();
con.start();
}
}
该代码得到以下输出
Producer puts 0
Producer puts 1
consumer gets 0
consumer gets 1
Producer puts 2
Producer puts 3
consumer gets 2
consumer gets 3
Producer puts 4
consumer gets 4
consumer gets 5
Producer puts 5
Producer puts 6
consumer gets 6
Producer puts 7
Producer puts 8
consumer gets 7
consumer gets 8
Producer puts 9
consumer gets 9
有人能解释一下这个代码出了什么问题吗?如何在这个代码中获得正确的顺序?
检查这两行:
val=c.get();
System.out.println("consumer gets "+val);
可能发生的情况是,消费者打电话给小房间,然后在那里等它空闲。然后它获取值并释放它。现在,在这两行之间——在c.get((之后和printlin之前,另一个线程可以完成整个过程——调用put(i(并打印。这时您将获得两个生产者.put((值。
您应该将打印部件移动到立方体孔代码内,以确保它打印出您想要的内容。