標籤:font href mil ++ 產品 bool 封裝 test nts
同樣是實驗存檔。//。。
依然以生產者消費者問題作為背景。
管程(=“資源管理程式”)將資源和對資源的操作封裝起來,資源使用者通過介面操作資源就 ok,不用去考慮進程同步的問題。
管程:
package entity.producerconsumer;public class Monition { private Buffer buffer; public Monition(int bufferSize) { buffer = new Buffer(bufferSize); } /** * 如果放入產品成功返回 true * @return */ public synchronized boolean put() { if (buffer.notFull()) { buffer.putItem(); return true; } return false; } /** * 如果取出產品成功返回 true * @return */ public synchronized boolean get() { if (buffer.notEmpty()) { buffer.getItem(); return true; } return false; } public String getStatus() { return "" + buffer; }}
生產者 & 消費者:
package entity.producerconsumer;public class Produc implements Runnable { /** * 統計生產者數量 */ private static int total = 0; /** * 生產者個體的 id */ private int id; private Monition PC; public Produc(Monition monition) { id = ++total; PC = monition; } @Override public void run() { while (true) { if (PC.put()) { // 如果操作成功列印緩衝區狀態 System.out.println(id + " 號生產者: " + PC.getStatus()); } } }}
/
package entity.producerconsumer;public class Consu implements Runnable { /** * 統計消費者數量 */ private static int total = 0; /** * 消費者個體的 id */ private int id; private Monition PC; public Consu(Monition monition) { id = ++total; PC = monition; } @Override public void run() { while (true) { if (PC.get()) { // 如果操作成功列印緩衝區狀態 System.out.println(id + " 號消費者: " + PC.getStatus()); } } }}
/
Buffer.java
測試:
package test;import entity.producerconsumer.Consu;import entity.producerconsumer.Monition;import entity.producerconsumer.Produc;public class MonitionTest { public static void main(String[] args) { Monition PC = new Monition(10); // 建立 5 個生產者和 5 個消費者 for (int i = 0; i != 5; ++i) { new Thread(new Produc(PC)).start(); new Thread(new Consu(PC)).start(); } }}
Java 管程解決生產者消費者問題