欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Lock、Condition实现简单的生产者消费者模式示例

程序员文章站 2024-02-25 22:57:27
复制代码 代码如下:package condition; import java.util.arraylist;import java.util.list;import...

复制代码 代码如下:

package condition;

import java.util.arraylist;
import java.util.list;
import java.util.concurrent.locks.condition;
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;


/**
 * 利用lock、condition实现生产者消费者模式
 * @author will
 *
 */
public class producerconsumerdemo {

 public static void main(string[] args) {
  int producercount = 10;
  int consumercount = 15;

  final producerconsumerdemo pcd = new producerconsumerdemo(5);   // 缓冲区大小为5

  thread[] producerthreads = new thread[producercount];
  for(int i = 0; i < producercount; i++) {
   producerthreads[i] = new thread("producer" + (i+1)) {

    @override
    public void run() {
     pcd.produce();
    }
   };
  }

  thread[] consumerthreads = new thread[consumercount];
  for(int j = 0; j < consumercount; j++) {
   consumerthreads[j] = new thread("consumer" + (j+1)) {
    @override
    public void run() {
     pcd.consume();
    }
   };
  }

  // 启动生产者消费者线程
  for(int i = 0; i < producercount; i++) {
   producerthreads[i].start();
  }
  for(int j = 0; j < consumercount; j++) {
   consumerthreads[j].start();
  }
 }

 private static final int default_buffer_size = 10;
 private int buffersize;   // 缓冲区大小
 private list<object> bufferlist;

 private final lock lock = new reentrantlock(true);
 private final condition condition = lock.newcondition();

 public producerconsumerdemo(int buffersize) {
  this.buffersize = buffersize > 0 ? buffersize : default_buffer_size;
  bufferlist = new arraylist<object>(buffersize);
 }

 // 生产
 public void produce() {
  lock.lock();   // 加锁
  try {
   while(bufferlist.size() == buffersize) {   // 缓冲区满了
    system.out.println("producer wait, thread: " + thread.currentthread().getname());
    condition.await();
   }

   // 生产
   bufferlist.add(new object());
   system.out.println("producer produce one, now buffer size: "
     + bufferlist.size() + ", and thread: " + thread.currentthread().getname());
   condition.signalall();   // 通知消费者
  } catch(interruptedexception e) {
   e.printstacktrace();
  } finally {
   lock.unlock();
  }
 }

 // 消费
 public void consume() {
  lock.lock();   // 加锁
  try {
   while(bufferlist.isempty()) {   // 缓冲区空了
    system.out.println("consumer wait, thread: " + thread.currentthread().getname());
    condition.await();
   }

   // 消费
   bufferlist.remove(0);   // 从链表头部移除一个
   system.out.println("consumer consumer one, now buffer size: "
     + bufferlist.size() + ", and thread: " + thread.currentthread().getname());
   condition.signalall();
  } catch(interruptedexception e) {
   e.printstacktrace();
  } finally {
   lock.unlock();
  }
 }

}