package dxc;
public class l7 {
public static void main(String[] args) {
Box box=new Box();
A a=new A(box);
B b=new B(box);
Thread a1=new Thread(a);
Thread b1=new Thread(b);
a1.start();
b1.start();
}
}
class Box{
int f=0;
int nai;
synchronized void put(int i) {
this.nai=i; //<---错误
if(f!=0)//有奶就不生产
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//this.nai=i; <---正确
System.out.println("生产者拿了第"+this.nai+"瓶奶");
f=1;
notifyAll();
}
synchronized void get() {
if(f==0)//没有奶就不拿
{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("消费者拿了第"+this.nai+"瓶奶");
f=0;
notifyAll();
}
}
class A implements Runnable{
Box box;
A(Box box)
{
this.box=box;
}
int i=1;
public synchronized void run(){
for(int i=1;i<=5;i++)
{
box.put(i);
}
}
}
class B implements Runnable{
Box box;
B(Box box)
{
this.box=box;
}
public synchronized void run(){
while(true)
{
box.get();
}
}
}
如果在错误那的话就是
生产者拿了第1瓶奶
消费者拿了第2瓶奶
生产者拿了第2瓶奶
消费者拿了第3瓶奶
生产者拿了第3瓶奶
消费者拿了第4瓶奶
生产者拿了第4瓶奶
消费者拿了第5瓶奶
生产者拿了第5瓶奶
消费者拿了第5瓶奶