本帖最后由 代臣 于 2012-3-20 08:23 编辑
- class Resource
- {
- private String name;
- private int count=1;
- private boolean flag=false;
- public synchronized void set(String name)
- {
- while(flag)
- try{this.wait();}catch(Exception e){}
- this.name=name+"--"+count++;
- System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
- flag=true;
- this.notifyAll();//改为了notifyAll
- }
- public synchronized void out()
- {
- while(!flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"...消费者......."+this.name);
- flag=false;
- this.notifyAll();//改为了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();
- }
- }
- }
- 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();
- }
- }
- //程序总是运行一会儿就卡住不动了,也没有报异常,这是怎么回事?
- /*
- 问题的症结是多个生产者和消费者线程存在的话,容易出现所有线程等待的情况,
- 解决的办法是利用notifyAll()方法唤醒所有的线程,其中就包括对方线程,因为线
- 程运行过程中可能会出现对方线程一直处于等待状态,比如消费者要消费的时候,
- 生产者并没有生产set()这个动作,因为该动作处于等待状态,没有Resource消费
- 者线程就无法进行下去,也就不能out(),从而产生所有线程等待的状况。
- */
复制代码 |