- /*
- 多生产者和多消费者 等待唤醒机制
- */
- class ThreadDemo_Producer_Consumer2
- {
- 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;
- //定义标记
- boolean flag=false;
- public synchronized void set(String name)
- {
- while(flag)
- try
- {
- wait();
- }
- catch (InterruptedException e)
- {
- }
- this.name=name+"---"+count;
- count++;
- System.out.println(Thread.currentThread().getName()+"...生产了,"+this.name);
- //将标记改为true
- flag=true;
- notifyAll();
- }
- public synchronized void get()
- {
- while(!flag)
- try
- {
- wait();
- }
- catch (InterruptedException e)
- {
- }
- System.out.println(Thread.currentThread().getName()+"...消费了.."+this.name);
- flag=!flag;
- notifyAll();
- }
- }
- //定义生产者的任务
- class Producer implements Runnable
- {
- private Resource r;
- Producer(Resource r)
- {
- this.r=r;
- }
- public void run()
- {
- while(true)
- {
- r.set("蛋糕");
- }
- }
- }
- //定义消费者的任务
- class Consumer implements Runnable
- {
- private Resource r;
- Consumer(Resource r)
- {
- this.r=r;
- }
- public void run()
- {
- while(true)
- {
- r.get();
- }
- }
- }
复制代码 |
|