生產者消費者模式筆記

synchronized

資源類

class Data {
    private int number = 0;

    public synchronized void increase() {
        while (number != 0) {
            // 等待
            try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "  " + number);
        // 通知喚醒
        notifyAll();
    }

    public synchronized void decrease() {
        while (number == 0) {
            // 等待
            try { wait(); } catch (InterruptedException e) { e.printStackTrace(); }
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "  " + number);
        // 通知喚醒
        notifyAll();
    }
}

線程操作資源類

public class Main {
    public static void main(String[] args) {
        Data data = new Data();
        
        new Thread(() -> { for (int i = 0; i < 10; i++) data.increase(); }, "A").start();

        new Thread(() -> { for (int i = 0; i < 10; i++) data.decrease(); }, "B").start();

        new Thread(() -> { for (int i = 0; i < 10; i++) data.increase(); }, "C").start();

        new Thread(() -> { for (int i = 0; i < 10; i++) data.decrease(); }, "D").start();
    }
}



Lock

資源類

class Data {
    private int       number    = 0;
    
    private Lock      lock      = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() {
        lock.lock();
        try {
            while (number != 0) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "  " + number);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        lock.lock();
        try {
            while (number == 0) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "  " + number);
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章