1. 程式人生 > >消費者與生產者---LinkedList方式模擬

消費者與生產者---LinkedList方式模擬

move nal lin class sleep ons 使用 sys 移除

采用LinkedList數據結構方式來模擬消費者與生產者模型,小Demo

import java.util.LinkedList;

public class MyQueue {

    private final LinkedList<Object> list = new LinkedList<>();
    
    private final Integer MAX = 5;
    
    private final Integer MIN = 0;
    
    private final Object obj = new Object();
    
    
    
public void put(Object object) { synchronized (obj) {
//判斷list裏面是否超過最大元素個數限制
while(list.size() == MAX) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
//往LinkedList添加元素 list.add(object); System.out.println(
"element " + object + " added" );
//喚醒消費者消費 obj.notify(); //notify需在synchronize方法塊內才可使用 } }
public Object get() { Object temp = null; synchronized
(obj) {
//判斷list是否有元素
while(list.size() == MIN) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
       //移除元素 temp
= list.removeFirst(); System.out.println("element " + temp + " consumer"); obj.notify(); } return temp; } public static void main(String[] args) { final MyQueue t = new MyQueue(); new Thread(new Runnable() { @Override public void run() { t.put("a"); t.put("b"); t.put("c"); t.put("d"); } },"t1").start(); new Thread(new Runnable() { @Override public void run() { try { t.get(); Thread.sleep(1000); t.get(); } catch (InterruptedException e) { e.printStackTrace(); } } },"t2").start(); } }

消費者與生產者---LinkedList方式模擬