//奶箱类
public class Box {
private int box = 0;
private boolean flag = false;
public synchronized void put(int box) {
if (flag==false) {
this.box = box;
System.out.println(Thread.currentThread().getName() + "放了第" + box + "奶");
flag = true;
notifyAll();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void get(int box) {
if (flag==true) {
this.box = box;
System.out.println(Thread.currentThread().getName() + "拿了第" + box + "奶");
flag = false;
notifyAll();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费者类
public class Customer implements Runnable {
private Box b;
public Customer(Box b) {
this.b = b;
}
@Override
public void run() {
for (int i = 1; i < 10; i++) {
b.get(i);
}
}
}
//生产者类
public class Producer implements Runnable {
private Box b;
public Producer(Box b) {
this.b = b;
}
@Override
public void run() {
for (int i = 1; i < 10; i++) {
b.put(i);
}
}
}
//测试类
public class Deom {
public static void main(String[] args) {
Box b=new Box();
Producer p=new Producer(b);
Customer c=new Customer(b);
Thread s1=new Thread(p,"送奶工");
Thread s2=new Thread(c,"消费者");
s1.start();
s2.start();
}
}
生产者消费者案例
最新推荐文章于 2024-07-10 03:02:05 发布