解析: 對於生產者消費者問題,要理清楚哪些資源是被併發訪問的,然後在此資源上加上適當的鎖就可以了。
/* * 生產者類:此生產者主要負責生產蘋果 */ public class ProduceThread extends Thread { private FruitBasket fb; public ProduceThread(FruitBasket fruitBasket) { this.fb = fruitBasket; } public void run() { try { //進行生產,並將生產的產品放進籃子 fb.produce(); } catch (InterruptedException e) { e.printStackTrace(); } } }
/* * 消費者類 */ public class CustomerThread extends Thread { private FruitBasket fb; // 消費者的名稱 private String customerName; // 消費者消費產品所用的時間 private long millisecond; public CustomerThread(FruitBasket fruitBasket, String customerName, long millisecond) { this.millisecond = millisecond; this.customerName = customerName; this.fb = fruitBasket; } @Override public void run() { try { while (true) { // 從果籃中拿出產品(消費產品) fb.consume(customerName); Thread.sleep(millisecond); System.out.println(customerName + "吃完了蘋果耗時" + millisecond / 1000 + "秒"); } } catch (InterruptedException e) { e.printStackTrace(); } } }
public class Main { public static void main(String[] args) { FruitBasket fruitBasket = new FruitBasket(); //生產者 ProduceThread produceThread = new ProduceThread(fruitBasket); //三個消費者 CustomerThread customerThread1 = new CustomerThread(fruitBasket, "孩子A", 3000); CustomerThread customerThread2 = new CustomerThread(fruitBasket, "孩子B", 2000); CustomerThread customerThread3 = new CustomerThread(fruitBasket, "孩子C", 4000); //開啓線程 produceThread.start(); customerThread1.start(); customerThread2.start(); customerThread3.start(); } } |
Java生產者消費者問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.