package pack01;import java.util.ArrayList;import java.util.List;/**?* 測試緩存區?* @author??*?*/public class TestBuffer { public static void main(String[] args) { List<Data> list = new ArrayList<Data>();//生成一個緩存區的儲存器 Buffer buffer = new Buffer(list,20);//生成一個緩存區 Consumer consumer = new Consumer(buffer);//生成一個消費者 Producer producer = new Producer(buffer);//生成一個生產者 new Thread(producer).start();//啟動線程 new Thread(consumer).start(); }}class Consumer implements Runnable//消費者{ private Buffer buffer;//為消費者指定緩存區 public Consumer(Buffer buffer) { //在構造器中指定緩存區 this.buffer = buffer; } public synchronized void consume()//消費 { if(this.buffer.dataBuffer.size() == 0) { System.out.println("緩存區中無數據可消費!"); try { this.wait();//如果緩存區中無數據可消費 暫停該線程 } catch (InterruptedException e) { e.printStackTrace(); } } this.buffer.dataBuffer.remove(this.buffer.dataBuffer.size()-1); this.buffer.len--;//緩存區的當前大小減1 this.notifyAll();//消費完畢 通知其他線程 } @Override public void run() { for(int i = 1; i < 10; i++) { this.consume(); System.out.println("消費第"+i+"個數據"); } } }class Producer implements Runnable//生產者{ private Buffer buffer;//為生產者指定容器 public Producer(Buffer buffer) { this.buffer = buffer;//在構造器中指定容器 } public synchronized void produce(Data data)//生產 { if(this.buffer.dataBuffer.size() == this.buffer.maxSize)//如果緩存區的大小等于緩存區的最大大小 { System.out.println("緩存區已滿!"); try { this.wait();//如果緩存區已滿 就暫停該線程 } catch (InterruptedException e) { e.printStackTrace(); } } this.buffer.dataBuffer.add(data);//如果不等 則往緩存區中加入data this.buffer.len++;//緩存區的當前大小加1 this.notifyAll();//生產完畢 通知其他線程 } @Override public void run() { for(int i = 1; i <= 20; i++) { this.produce(new Data(i)); System.out.println("生產第"+i+"個數據"); } }}class Buffer//緩存區{ List <Data> dataBuffer;//指定一個儲存data的容器 int maxSize;//指定緩存區的最大大小 int len;//指定緩存區的當前大小 public Buffer(List <Data> dataBuffer, int maxSize) { //在構造時 設置緩存區的的大小 this.dataBuffer = dataBuffer; this.maxSize = maxSize; this.len = this.dataBuffer.size(); } }class Data{ int id;//指定id public Data(int id) { this.id = id; } }
2 回答
添加回答
舉報
0/150
提交
取消
