標籤:
正好有人問,就直接將代碼記錄下來。
背景:有一個倉庫儲存貨物,存在著生產者和消費者,設計一個可以並發的實現。
設計思路:設計一個倉庫類,類中儲存最大的容量限制和當前的count,類中包含生產和消費的方法,並且都是synchronized。
具體代碼:
package com.test.tiny;public class Store { private final int MAX_SIZE; //最大 private int count; // 當前 public Store(int n) { MAX_SIZE = n; count = 0; } public synchronized void add() { while(count >= MAX_SIZE) { System.out.println("已經滿了"); try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count++; System.out.println(Thread.currentThread().toString() + " put :" + count); this.notifyAll(); } public synchronized void remove() { while(count <= 0) { System.out.println("已經空了"); try { this.wait(); }catch(Exception e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().toString() + " get :" + count); count--; this.notifyAll(); } public static void main(String[] args) { // TODO Auto-generated method stub Store s = new Store(5); Thread pro = new Producer(s); Thread con = new Consumer(s); Thread pro2 = new Producer(s); Thread con2 = new Consumer(s); pro.setName("生產者1"); con.setName("消費者1"); pro2.setName("生產者2"); con2.setName("消費者2"); pro.start(); con.start(); pro2.start(); con2.start(); }}class Producer extends Thread { private Store s; public Producer(Store s) { this.s = s; } public void run() { while(true) { s.add(); try { Thread.sleep(1000); // 為了直觀,休息1秒 }catch(Exception e) { e.printStackTrace(); } } }}class Consumer extends Thread { private Store s; public Consumer(Store s) { this.s = s; } public void run() { while(true) { s.remove(); try { Thread.sleep(1500); // 為了直觀 多休息0.5秒 } catch (InterruptedException e) { e.printStackTrace(); } } }}
[JAVA 多線程] 生產者消費者執行個體