Java 生產(chǎn)者消費(fèi)者實(shí)現(xiàn)

《Java 編程思想》中,使用 廚師-服務(wù)員 來表示:生產(chǎn)者、消費(fèi)者。

思路

chef 在 有 meal 的時(shí)候,會釋放鎖;在制作 meal 時(shí),會獲取 waitPerson 的鎖,制作完 meal 后,喚醒所有的 waitPerson;

waitPerson 在 沒有 meal 的時(shí)候,會釋放鎖;在消費(fèi) meal 后,會將 meal 置為 null,操作期間需要獲得 chef 的鎖。

實(shí)現(xiàn)

public class Restaurant {
    Meal meal;
    ExecutorService exec = Executors.newCachedThreadPool();
    WaitPerson waitPerson = new WaitPerson(this);
    Chef chef = new Chef(this);
    
    public Restaurant() {
        exec.execute(chef);
        exec.execute(waitPerson);
    }
    
    public static void main(String[] args) {
        new Restaurant();
    }
}
public class Meal {
    
    private final int orderNum;
    
    public Meal(int orderNum) {
        this.orderNum = orderNum;
    }
    
    @Override
    public String toString() {
        return "Meal " + orderNum;
    }
}
public class Chef implements Runnable{
    private int count = 0;
    private Restaurant restaurant;
    
    public Chef(Restaurant restaurant) {
        this.restaurant = restaurant;
    }
    
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) { // shutdownNow 后,會退出循環(huán)
                synchronized (this) {
                    // 如果有 meal,則釋放鎖,等待
                    while (restaurant.meal != null) {
                        wait();
                    }
                }
                if (++ count == 10) {
                    System.out.println("Out of 10");
                    restaurant.exec.shutdownNow();
                }
                synchronized (restaurant.waitPerson) {
                    restaurant.meal = new Meal(count);
                    restaurant.waitPerson.notifyAll();
                }
                TimeUnit.SECONDS.sleep(1);
            }
            
        } catch (Exception e) {
            System.out.println("Chef interrupted");
        }
    }
}
public class WaitPerson implements Runnable{
    
    private Restaurant restaurant;
    
    public WaitPerson(Restaurant restaurant) {
        this.restaurant = restaurant;
    }
    
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                synchronized (this) {
                    while (restaurant.meal == null) {
                        wait();
                    }
                }
                System.out.println("WaitPerson got " + restaurant.meal);
                synchronized (restaurant.chef) {
                    restaurant.meal = null;
                    restaurant.chef.notifyAll();
                }
            }
        } catch (Exception e) {
            System.out.println("WaitPerson interrupted");
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容