java解决单缓冲生产者消费者问题示例
经典的生产者消费者问题模拟。此程序模拟最简单情形——单缓冲。为模拟实际情况,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]
下一篇: Java编程实现对象克隆(复制)代码详解