public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource r = new Resource();
Producer pro = new Producer(r);
Consumer con = new Consumer(r);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resource {
private String name;
private int count = 1;
private boolean flag = false; //flag用于判断本商品是否可被消费
public synchronized void set(String name) { // 向资源池中放入商品,并将flag置为true,表示此商品现在可以被消费
while (flag)
try {
this.wait();
} catch (InterruptedException e) {
}
this.name = name + "==" + (count++);
System.out.println(Thread.currentThread().getName() + "==producer==" + this.name);
flag = true;
this.notifyAll();
}
public synchronized void out() { // 从资源池中消费掉商品,并将flag置为false,表示本商品已经被消费了,所以不能再用了。
while (!flag)
try {
this.wait();
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName() + "====consumer====" + this.name);
flag = false;
this.notifyAll();
}
}
class Producer implements Runnable {
private Resource res;
Producer(Resource res) {
this.res = res;
}
public void run() {
while (true)
res.set("+商品+");
}
}
class Consumer implements Runnable {
private Resource res;
Consumer(Resource res) {
this.res = res;
}
public void run() {
while (true)
res.out();
}
}
生产者消费者模型--修改多个线程的情况
最新推荐文章于 2020-07-14 11:24:05 发布