public class Synchronized { public static void main(String[] args) { Factory f = new Factory();// ---------------------------------------建立Factory工廠實例 Thread t1 = new Thread() {// ---------------------------------------線程1(生產) public void run() { f.sc();// --------------------------------------------------調用工廠的生產方法 } }; Thread t2 = new Thread() {// ---------------------------------------線程2(消費) public void run() { f.xf();// --------------------------------------------------調用工廠的消費方法 } }; t1.start();// ------------------------------------------------------啓動生產方法線程 t2.start();// ------------------------------------------------------啓動消費方法線程 } } //****************************************************************************************************** class Factory {// ----------------------------------------------------------工廠 int rl = 10;// ---------------------------------------------------------倉庫容量 int sl = 3;// ----------------------------------------------------------實際商品(庫存)數量 public void sc() {// ---------------------------------------------------生產方法 try { while (true) {// -----------------------------------------------循環監聽 Thread.currentThread().sleep(// ----------------------------生產速度(隨機,比消費速度慢,隨機數加了200) (int) (Math.random() * 1000 + 200)); synchronized (this) {// ------------------------------------同步鎖 System.out.println("生產商品\t庫存:" + (++sl));//--------進行生產 if (sl >= rl) {// --------------------------------------判斷是否滿倉 System.out.println("倉庫滿了,中止生產"); this.wait();// -------------------------------------中止生產 System.out.println("*************************繼續生產"); } if (sl == 6) { this.notify();// -----------------------------------通知消費(設置了商品緩存,庫存爲0時,生產6件商品以上才通知消費方法) } } } } catch (Exception e) { e.printStackTrace(); } } public void xf() {// ---------------------------------------------------消費方法 try { while (true) {// -----------------------------------------------循環監聽 Thread.currentThread().sleep((int) (Math.random() * 1000));//消費速度(隨機) synchronized (this) {// ------------------------------------同步鎖 System.out.println("消費商品\t庫存:" + (--sl) + "-----");//進行消費 if (sl <= 0) {// ---------------------------------------判斷是否空倉 System.out.println("倉庫沒有商品了,中止消費"); this.wait();// -------------------------------------中止消費 System.out.println("*************************繼續消費"); } this.notify();// ---------------------------------------通知生產(運行到這裏,意味這商品必定被消費了,工廠就開始生產) } } } catch (Exception e) { e.printStackTrace(); } } }
消費速度比生產速度塊,因此基本看不到滿倉的狀況,你能夠本身調一下二者之間的速度,這樣就能夠看到滿倉的提示了。緩存
運行結果dom