6.2 second case

1. Producer and consumer interaction

1. 1

1. The shop assistant

class Clerk {
    private int product = 0;

    /** ** */
    public synchronized void get(a) {
        if (product >= 10) {
            System.out.println("The product is full");
        } else {
            System.out.println(Thread.currentThread().getName()+":"+ ++product); }}/** ** sell goods */
    public synchronized void sale(a) {
        if (product <= 0) {
            System.out.println("Shortage");
        } else {
            System.out.println(Thread.currentThread().getName()+":"+ --product); }}}Copy the code

2. Producers

class Productor implements Runnable {
    private Clerk clerk;

    public Productor(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run(a) {
        for (int i = 0; i < 20; i++) { clerk.get(); }}}Copy the code

3. Consumers

class Consumer implements Runnable {
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run(a) {
        for (int i = 0; i < 20; i++) { clerk.sale(); }}}Copy the code

The results of

Problems above: repeated replenishment, repeated consumption, lack of wake-up mechanism

2. 2

Increased arousal

While the wake up problem is resolved, there is a risk of waiting forever

3. 3

False awakenings occur when there are multiple producers/consumers

code

	public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Productor productor = new Productor(clerk);
        Consumer consumer = new Consumer(clerk);

        new Thread(productor, "Producer A").start();
        new Thread(consumer, "Consumer B").start();

        new Thread(productor, "Producer C").start();
        new Thread(consumer, "Consumer D").start();
    }
Copy the code

The results of

Solutions:

    /** ** */
    public synchronized void get(a) {
        while (product >= 1) {
            System.out.println("The product is full");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ":" + ++product);
        this.notifyAll();
    }

    /** ** sell goods */
    public synchronized void sale(a) {
        while (product <= 0) {
            System.out.println("Shortage");
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + ":" + --product);
        this.notifyAll();
    }
Copy the code

If a while