Producers and consumers --synchronized

# Code

public class App {

    public static void main(String[] args) {

        Depot depot = new Depot(100);
        Producer producer = new Producer(depot);
        Consumer consumer = new Consumer(depot);

        producer.produce(60);
        consumer.consume(100);
        producer.produce(90);
        consumer.consume(40);

    }
}

class Depot {
    // 仓库最大容量
    private int capacity;
    // 仓库目前容量
    private int size;

    public Depot(int capacity) {
        this.size = 0;
        this.capacity = capacity;
    }

    public synchronized void produce(int val) {
        try {
            int surplus = val;
            while (surplus > 0) {
                while (size >= capacity) {
                    wait();
                }
                int incre = (size + surplus) > capacity ? (capacity - size) : surplus;
                size += incre;
                surplus -= incre;
                System.out.printf("%s plan to produce (%d), actually produce (%d), depot size (%d) \n",
                        Thread.currentThread().getName(), val, incre, size);
                notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void consume(int val) {
        try {
            int surplus = val;
            while (surplus > 0) {
                while (size <= 0) {
                    wait();
                }
                int desc = (size < surplus) ? size : surplus;
                size -= desc;
                surplus -= desc;
                System.out.printf("%s plan to consume (%d), actutally consume (%d), depot size (%d) \n",
                        Thread.currentThread().getName(), val, desc, size);
                notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Producer {
    private Depot depot;

    public Producer(Depot depot) {
        this.depot = depot;
    }

    public void produce(final int val) {
        new Thread() {
            public void run() {
                depot.produce(val);
            }
        }.start();
    }
}

class Consumer {
    private Depot depot;

    public Consumer(Depot depot) {
        this.depot = depot;
    }

    public void consume(final int val) {
        new Thread() {
            public void run() {
                depot.consume(val);
            }
        }.start();
    }
}

# Output:

Thread-0 plan to produce (60), actually produce (60), depot size (60)
Thread-3 plan to consume (40), actutally consume (40), depot size (20)
Thread-2 plan to produce (90), actually produce (80), depot size (100)
Thread-1 plan to consume (100), actutally consume (100), depot size (0)
Thread-2 plan to produce (90), actually produce (10), depot size (10)

Guess you like

Origin www.cnblogs.com/lwmp/p/11512636.html