前言下面我們直接上**,通過乙個案例來展示。本篇詳細講解生產者消費者模式的幾種實現方式。
public class consumetest2
static class consumerimpl implements runnable catch (interruptedexception e)
}string removename = list.remove(0);
system.out.println("消費了:" + removename + "--剩餘產品數量:" + list.size());
try catch (interruptedexception e)
list.notify();}}
}}
static class productimpl implements runnable catch (interruptedexception e)
}string name = "product:" + (list.size() + 1);
list.add(name);
system.out.println("新增了產品:" + name + "--剩餘空間:" + (5 - list.size()));
try catch (interruptedexception e)
list.notify();}}
}}
}//列印資訊
size = 0, consume wait
新增了產品:product:1--剩餘空間:4
新增了產品:product:2--剩餘空間:3
新增了產品:product:3--剩餘空間:2
新增了產品:product:4--剩餘空間:1
新增了產品:product:5--剩餘空間:0
size = 5, product wait
consume wait finish
消費了:product:1--剩餘產品數量:4
消費了:product:2--剩餘產品數量:3
消費了:product:3--剩餘產品數量:2
消費了:product:4--剩餘產品數量:1
消費了:product:5--剩餘產品數量:0
size = 0, consume wait
public class consumetest3
static class consumerimpl implements runnable catch (interruptedexception e)
}string removename = list.remove(0);
system.out.println("消費了:" + removename + "--剩餘產品數量:" + list.size());
try catch (interruptedexception e)
product.signal();
} finally }}
}static class productimpl implements runnable catch (interruptedexception e)
}string name = "product:" + (list.size() + 1);
list.add(name);
system.out.println("新增了產品:" + name + "--剩餘空間:" + (5 - list.size()));
try catch (interruptedexception e)
consume.signal();
} finally }}
}}
public class consumetest4
static class consumerimpl implements runnable catch (interruptedexception e) }}
}static class productimpl implements runnable catch (interruptedexception e) }}
}}
生產者消費者 生產者與消費者模式
一 什麼是生產者與消費者模式 其實生產者與消費者模式就是乙個多執行緒併發協作的模式,在這個模式中呢,一部分執行緒被用於去生產資料,另一部分執行緒去處理資料,於是便有了形象的生產者與消費者了。而為了更好的優化生產者與消費者的關係,便設立乙個緩衝區,也就相當於乙個資料倉儲,當生產者生產資料時鎖住倉庫,不...
生產者 消費者模式
一 我哥們把資料存入redis快取區 生產者 二 我從緩衝器取資料,並作處理!消費者 詳細 如下 取訂單並判斷 redis new redis conn flag redis connect redis translate usefull host,redis translate usefull p...
生產者消費者模式
常見場景 某個模組負責產生資料,這些資料由另乙個模組來負責處理。產生資料的模組,就形象地稱為生產者 而處理資料的模組,就稱為消費者。該模式還需要有乙個緩衝區處於生產者和消費者之間,作為乙個中介。生產者把資料放入緩衝區,而消費者從緩衝區取出資料 緩衝區作用 1.解耦,生產者和消費者只依賴緩衝區,而不互...