java解決單緩沖生產(chǎn)者消費者問題示例
經(jīng)典的生產(chǎn)者消費者問題模擬。此程序模擬最簡單情形——單緩沖。為模擬實際情況,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 生產(chǎn)者消費者模式(詳細分析)
- Java多線程之線程通信生產(chǎn)者消費者模式及等待喚醒機制代碼詳解
- JAVA生產(chǎn)者消費者(線程同步)代碼學(xué)習(xí)示例
- java多線程解決生產(chǎn)者消費者問題
- JAVA多線程實現(xiàn)生產(chǎn)者消費者的實例詳解
- Java實現(xiàn)生產(chǎn)者消費者問題與讀者寫者問題詳解
- java并發(fā)學(xué)習(xí)之BlockingQueue實現(xiàn)生產(chǎn)者消費者詳解
- java 中多線程生產(chǎn)者消費者問題詳細介紹
- Java基于Lock的生產(chǎn)者消費者模型示例
- Java生產(chǎn)者消費者模式實例分析
相關(guān)文章
Maven學(xué)習(xí)----Maven安裝與環(huán)境變量配置教程
這篇文章主要給大家介紹了關(guān)于如何利用Maven入手Spring Boot第一個程序的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-06-06
SpringBoot整合Graylog做日志收集實現(xiàn)過程
這篇文章主要為大家介紹了SpringBoot整合Graylog做日志收集實現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-12-12
Shiro整合Springboot和redis,jwt過程中的錯誤shiroFilterChainDefinition問
這篇文章主要介紹了Shiro整合Springboot和redis,jwt過程中的錯誤shiroFilterChainDefinition問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
Java xml數(shù)據(jù)格式返回實現(xiàn)操作
這篇文章主要介紹了Java xml數(shù)據(jù)格式返回實現(xiàn)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

