`
砺雪凝霜
  • 浏览: 152161 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

生产者和消费者

阅读更多

                                                     生产者和消费者

 java 1.5以后用
1. lock.lock()
      同步代码
     lock.unlock()
替代了synchronized同步代码块
2.condition.await()替代了wait();
3.condition.signal替代了notify
4.condition.signalAll()替代了notifyAll

public class ProducersAndConsumer {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Resource re = new Resource(1);
  new Thread(new Producer(re)).start();//t1
  new Thread(new Producer(re)).start();//t2
  new Thread(new Consumer(re)).start();//t3
  new Thread(new Consumer(re)).start();//t4

 }

}

class Resource {
 private String name;
 private int count;
 boolean flag;

 public Resource(int count) {
  this.count = count;
 }

 /*
  * t1等待 t2在等待 t3没启动 t4没启动
  * t3启动 t1唤醒 t2在等待 t4没启动
  * t3等待 t1唤醒 t2在等待 t4等待
  * t1启动 t2被唤醒 t3在等待 t4等待
  *  此时t2不会判断标志位就往下执行了,导致生产了多次,只消费了1次的情况

  * 所以我加了一个while循环来防止这种问题的发生

  */
 private Lock lock = new ReentrantLock();
 private Condition condition = lock.newCondition();

 public void set(String name) {
  lock.lock();
  try {
   while (flag) {
      condition.await();  // java1.5以前的写法this.wait();
   }
   this.name = name + "---" + count++;
   flag = true;
   System.out.println(Thread.currentThread().getName()
     + ".....生产了ipnone" + count);
        condition.signalAll(); //java1.5以前的写法: this.notifyAll();
  } catch (InterruptedException e) {
   e.printStackTrace();
  } finally {
   lock.unlock();
  }
 }

 public void out() {
  lock.lock();
  try {
   while (!flag) {
    condition.await();// java1.5以前的写法 this.wait();
   }
   System.out.println(Thread.currentThread().getName()
     + "----消费了iphone" + count);
   condition.signalAll();// java1.5以前的写法 this.notifyAll();
   flag = false;
  } catch (InterruptedException e) {
   e.printStackTrace();
  }finally{
   lock.unlock();
  }
 }
}

class Producer implements Runnable {
 private Resource res;

 public Producer(Resource res) {
  this.res = res;
 }

 @Override
 public void run() {
  while (true) {
   res.set("iphone");
  }
 }

}

class Consumer implements Runnable {
 private Resource res;

 public Consumer(Resource res) {
  this.res = res;
 }

 @Override
 public void run() {
  while (true) {
   res.out();
  }
 }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics