生产者/消费者--并发

产品类

// 产品类
public class Apple {
    private String apple;

    public String getApple() {
        return apple;
    }

    public void setApple(String apple) {
        this.apple = apple;
    }

    public Apple(String apple) {
        this.apple = apple;
    }
    
    public Apple() {
        
    }
}

产品池类

// 产品池
public class ProductPool {
    private List<Apple> apples;
    private int maxSize = 0;
    public ProductPool(int maxSize) {
        this.apples = new ArrayList<Apple>();
        this.maxSize = maxSize;
    }
    public synchronized void push(Apple apple) {
        if (this.apples.size() == maxSize) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("ERROR");
            }
        }
        this.apples.add(apple);
        this.notifyAll();
    }
    public synchronized Apple pop() {
        if (this.apples.size()==0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("ERROR");
            }
        }
        Apple apple = this.apples.remove(0);
        this.notifyAll();
        return apple;
    }
}

生产者

// 生产者
public class Product extends Thread {
    private ProductPool pool;
    public Product(ProductPool pool) {
        this.pool = pool;
    }
    @Override
    public void run() {
        while (true) {
            String name = "产品号:" + (int)(Math.random()*100);
            System.out.println("生产者生产了1件Apple,产品号:" + name);
            Apple apple = new Apple(name);
            this.pool.push(apple);
        }
    }
}

消费者

// 消费者
public class Consumer extends Thread {
    private ProductPool pool;
    public Consumer(ProductPool pool) {
        this.pool = pool;
    }
    @Override
    public void run() {
        while (true) {
            Apple apple = this.pool.pop();
            System.out.println("消费者消费了一件产品:" + apple.getApple());
        }
    }
}

运行主类

public class Client {
    public static void main(String[] args) {
        ProductPool pool = new ProductPool(15);
        new Product(pool).start();
        new Consumer(pool).start();
    }
}

猜你喜欢

转载自www.cnblogs.com/fanqinglu/p/11929630.html