生产和消费

package service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

interface Service {
}
interface ServiceProvider extends Service {
    V get();
    void set(V v);
}
interface Product {

}
class Tmall implements ServiceProvider {
    private List storage;
    private int MAX_COUNT;
    private int count;

    private Tmall(int maxCount) {
        storage = Collections.synchronizedList(new ArrayList<>(maxCount));
        MAX_COUNT = maxCount;
    }

    // 消费者线程消费的方法
    @Override
    public synchronized Product get() {
        while (count <= 0) {
            try {
                System.out.println("库存没了,消费者等待");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Product product = storage.remove(--count);
        System.out.println(Thread.currentThread().getName() + "消费者消费,当前库存为:" + count);
        notifyAll(); //通知生产者线程生产
        return product;
    }

    // 生产者线程生产的方法
    @Override
    public synchronized void set(Product product) {
        while (count >= MAX_COUNT) {
            try {
                System.out.println("库存满了,生产者等待");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.add(product);
        count++;
        System.out.println(Thread.currentThread().getName() + "生产者生产,当前库存为:" + count);
        notifyAll(); // 通知消费者线程消费
    }

    public static class Producer implements Runnable {
        private Tmall tmall;

        Producer(Tmall tmall) {
            this.tmall = tmall;
        }
        @Override
        public void run() {
            while (true) {
                tmall.set(new Item());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static class Consumer implements Runnable {
        private Tmall tmall;

        Consumer(Tmall tmall) {
            this.tmall = tmall;
        }
        @Override
        public void run() {
            while (true) {
                Product product = tmall.get();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static class Item implements Product {}

    public static void main(String[] args) {
        Tmall tmall = new Tmall(10);
        Producer p = new Producer(tmall);
        Consumer c = new Consumer(tmall);
        new Thread(p).start();
        new Thread(p).start();
        new Thread(p).start();
        new Thread(c).start();
    }
}

你可能感兴趣的:(生产和消费)