本帖最后由 新语新空 于 2014-8-7 17:49 编辑
毕老师的视频里讲,如果用if判断flag可能会发生两个生产者(或者消费者)连续执行的情况,因为被唤醒的线程往下执行if语句。为什么换成while以后不是继续往下执行,而是返回判断flag呢?
而事实上,这样好像也可行。我运行过几次,确实没有出现问题。
- class ProduceConsumerDemo
- {
- 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();
-
- //new Thread(new Producer(r)).start();
- //new Thread(new Consumer(r)).start();
- }
- }
- class Resource
- {
- private String name;
- private int count = 1;
- private boolean flag;
-
- 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 out()
- { 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.out();
- }
- }
- }
复制代码 |
|