- package ceshi;
- class ProducerConsumerDemo
- {
- public static void main(String[] args)
- {
- Resource r = new Resource();
- //启动生产者和消费者线程
- new Thread(new Producer1(r)).start();
- new Thread(new Producer1(r)).start();
- new Thread(new Consumer1(r)).start();
- new Thread(new Consumer1(r)).start();
- new Thread(new Consumer1(r)).start();
- }
- }
- class Resource
- {
- private String name;
- private int count = 1;
- private boolean flag = false;//标志变量,代表商品的有无
- public synchronized void make(String name)
- {
- while(flag)//flag为true,表明正在消费商品,需等待
- try{this.wait();}catch(Exception e){}
- this.name = name+"..."+count++;
- System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
- flag = true;//有商品了
- this.notifyAll();//唤醒所有的等待线程
- }
- public synchronized void eat()
- {
- while(!flag)//flag为false,则等待,即只有flag为true时,才有商品可以进行消费
- try{wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"---消费者........."+this.name);
- flag = false;//商品被消费完了
- this.notifyAll();
- }
- }
- class Producer1 implements Runnable
- {
- private Resource res;
- Producer1(Resource res)
- {
- this.res = res;
- }
- public void run()
- {
- while(true)
- {
- res.make("+商品+");
- }
- }
- }
- class Consumer1 implements Runnable
- {
- private Resource res;
- Consumer1(Resource res)
- {
- this.res = res;
- }
- public void run()
- {
- while(true)
- {
- res.eat();
- }
- }
- }
复制代码 |
|