安全锁实现生产者与消费者案例

  • Post author:
  • Post category:其他



public class SafetyLock {

    public static void main(String[] args) {

        Data data = new Data();

        new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "A").start();

        new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "B").start();

        new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "C").start();

        new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "D").start();

    }

}

class Data {

    private static int number = 0;

    public synchronized void increment() throws InterruptedException {

        while (number != 0) {

            this.wait();
        }
        
        number++;
        System.out.println(Thread.currentThread().getName() + "=>" + number + "\t生产");

        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
    
        while (number == 0) {

            this.wait();
        }
        
        number--;
        System.out.println(Thread.currentThread().getName() + "=>" + number + "\t消费");

        this.notifyAll();
    }
}



版权声明:本文为ZHOU020710原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。