Java高併發編程(6)

使用synchronized、wait、notify實現的生產者、消費者

public class ProducterAndCustomerVersion1 {
    private final static Object LOCK = new Object();
    private static boolean isProducted = false;
    private static int nums = 0;
    /**
     * 生產者
     */
    public static void producter(){
        synchronized (LOCK){
            if (!isProducted){
                //未生產,需要生產
                nums++;
                isProducted = true;
                System.out.println("生產者生產產品:"+nums);
            }
            //已生產,需要喚醒消費者,然後等待消費者消費
            LOCK.notify();
            try {
                LOCK.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 消費者
     */
    public static void customer(){
        synchronized (LOCK){
            if (isProducted){
                isProducted = false;
                System.out.println("消費者消費產品:"+nums);
            }
            LOCK.notify();
            try {
                LOCK.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            while (true){
                ProducterAndCustomerVersion1.producter();
            }
        });
        Thread thread2 = new Thread(() -> {
            while (true){
                ProducterAndCustomerVersion1.customer();
            }
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章