- /*
- 对于多个生产者和消费者
- 为什么要定义while判断标识
- 因为:被唤醒的线程再一次判断标识
- 【为什么要定义notfiyAll
- 因为需要唤醒对方的线程
- 因为只用notfiy,容易出现只唤醒本方线程的情况,导致程序中的所有线程都等待
- */
- class Rerource
- {
- private String name;
- private int count=1;
- private boolean flag=false;
-
- public synchronized void set(String name)
- {
- while(this.flag)
- try{this.wait();}catch(Exception e){}
- this.name=name+"---"+count++;
- System.out.println(Thread.currentThread().getName()+".....生产者...."+this.name);
- this.flag=true;
- this.notifyAll();
- }
- public synchronized void get()
- {
- while(!this.flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+".....消费者..........."+this.name);
- this.flag=false;
- this.notifyAll();
- }
- }
- class Product implements Runnable
- {
- Rerource re=new Rerource();
- Product(Rerource re)
- {
- this.re=re;
- }
- public void run()
- {
- while(true)
- {
- re.set("+商品+");
- }
- }
- }
- class Consumer implements Runnable
- {
- Rerource re=new Rerource();
- Consumer(Rerource re)
- {
- this.re=re;
- }
- public void run()
- {
- while(true)
- {
- re.get();
- }
- }
- }
- public class ProductConsumerDome {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Rerource r=new Rerource();
- Product p=new Product(r);
- Consumer c=new Consumer(r);
- Thread t1=new Thread(p);
- Thread t2=new Thread(p);
- Thread t3=new Thread(c);
- Thread t4=new Thread(c);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 新手上路,多多指教
|
|