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

java解决单缓冲生产者消费者问题示例

程序员文章站 2024-02-26 14:40:16
经典的生产者消费者问题模拟。此程序模拟最简单情形——单缓冲。为模拟实际情况,consume item和produce item时加了延时,可以通过修改延时模拟不同的生成消费...

经典的生产者消费者问题模拟。此程序模拟最简单情形——单缓冲。为模拟实际情况,consume item和produce item时加了延时,可以通过修改延时模拟不同的生成消费速率。

[code]

[/co/**
 * single buffer consumer-producer problem.
 * by xu(xusiwei1236@163.com).
 * */
public class consumerproducer {

 static object buffer = null;

 static object mutex = new object();

 static object condconsumer = new object();

 static object condproducer = new object();

 public static void main(string[] args) {
  thread producer = new thread() {
   public void run() {
//    for(int i=0; i<10; i++) {
    for(int i=0; ; i++) {
     // produce item.
     try {
      thread.sleep(1000);
     } catch (interruptedexception e) {
      e.printstacktrace();
     }
     string item = new string("item-" + i);
     system.out.println("[producer] produced " + item);

     // wait for buffer empty.
     synchronized (condproducer) {
      while(buffer != null) {
       try {
        condproducer.wait();
       } catch (interruptedexception e) {
        e.printstacktrace();
       }
      }
     }

     // put item to buffer.     
     synchronized (mutex) {
      buffer = item;
      system.out.println("[producer] put " + item + " to buffer.");
     }

     // notify consumers.
     synchronized (condconsumer) {
      condconsumer.notify();
     }
    }
   }
  };

  thread consumer = new thread() {
   public void run() {
//    for(int i=0; i<10; i++) {
    for( ; ; ) {
     // wait for item come.
     synchronized (condconsumer) {
      while( buffer == null ) {
       try {
        condconsumer.wait();
       } catch (interruptedexception e) {
        e.printstacktrace();
       }
      }
     }

     // get item from buffer.
     string item = null;
     synchronized (mutex) {
      item = (string)buffer;
      buffer = null;
      system.out.println("  [consumer] get " + item + " from buffer.");
     }

     // consume item.
     try {
      thread.sleep(500);
     } catch (interruptedexception e) {
      e.printstacktrace();
     }
     system.out.println("  [consumer] comsumed " + item);

     // notify producers.
     synchronized (condproducer) {
      condproducer.notify();
     }
    }
   }
  };

  consumer.start();
  producer.start();
 }
}de]