package n1;
public class main {
public static void main(String[] args) {
Box b=new Box();
xfz i=new xfz(b);
scz y=new scz(b);
Thread i1=new Thread(i);
Thread y1=new Thread(y);
i1.start();
y1.start();
}
}
class Box {
int nai=0;
public synchronized void getNai() {
if(nai>=1) {
System.out.println("消费者拿了第"+nai+"瓶奶");
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
notifyAll();
}
}
public synchronized void setNai(int nai) {
this.nai = nai;
System.out.println("生产者生产了第"+nai+"瓶奶");
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
notifyAll();
}
}
}
class xfz implements Runnable{
Box box;
public xfz(Box box) {
super();
this.box = box;
}
public void run() {
while(true)
{
box.getNai();
}
}
}
class scz implements Runnable {
Box box;
public scz(Box box) {
super();
this.box = box;
}
public void run() {
for(int i=1;i<=5;i++)
{
box.setNai(i);
}
}
}
Box 那里的if(nai>=1) 改成while(nai>=1)