现有一个包子铺, 有两名员工在不停的做包子, 一秒钟做一个, 当包子铺的包子总数达到100的时候, 停止做包子. 现有多名顾客同时吃包子, 当包子已经吃完的时候, 等着员工生产包子, 当有了包子就继续吃
public class test {
static int num =0;
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
while(true) {
synchronized (Lock.class) {
if (num<100) {
num++;
System.out.println(Thread.currentThread().getName()+"做了第一个包子");
}else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
};
Thread t1 = new Thread(r, "工人一");
Thread t2 = new Thread(r, "工人二");
Runnable r2 = new Runnable() {
public void run() {
while(true) {
synchronized (Lock.class) {
if (num>0) {
System.out.println(Thread.currentThread().getName()+"个顾客吃了一个包子");
num--;
}else {
System.out.println("包子没啦,赶紧做,我要吃包子...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
};
Thread c1 = new Thread(r2,"顾客一");
Thread c2 = new Thread(r2, "顾客二");
t1.start();
t2.start();
c1.start();
c2.start();
}