生产者和消费者问题中的notify()和notifyAll();
使用有和区别,为何notify()可以避免问题
- class Resource
- {
- private String name;
- private int count = 1;
- boolean flag = false;
- public synchronized void set(String name)
- {
- while(flag)
- try{wait();}catch(Exception e){}
- this.name = name+"-----"+count++;
- System.out.println(Thread.currentThread().getName()+"-生产者--"+this.name);
- flag = true;
- this.notifyAll();
- }
- public synchronized void get()
- {
- while(!flag)
- try{wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"消费者&&&&&&&"+this.name);
- flag = false;
- this.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();
- }
-
- }
- class ProducerConsumer
- {
- public static void main(String[] args)
- {
- Resource r = new Resource();
- Producer p = new Producer(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();
- }
- }
复制代码 |
|