java生產者、消費者—線程安全

 

 

1、產品

/**
 * 產品
 * Created by hgg on 2019/9/29.
 */
public class Product {
    private String name;

    public Product(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

2、產品池


import java.util.LinkedList;
import java.util.List;

/**
 * 產品池
 * Created by hgg on 2019/9/29.
 */
public class ProductPool {

    //產品集合,生產者生產,消費者消費
    private List<Product> productList;

    private int MAX_SIZE = 0;

    public ProductPool(int maxSize){
        this.productList = new LinkedList<Product>();
        this.MAX_SIZE = maxSize;
    }

    /**
     * 生產—放入產品池
     * @param product
     */
    public synchronized void push(Product product)  {
        if (productList.size() == MAX_SIZE){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            productList.add(product);
            this.notifyAll();
        }
    }

    /**
     * 每次取出第一個元素
     * @return
     */
    public synchronized Product pop() {
        Product product = null;
        if (this.productList.size() == 0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        product = productList.remove(0);
        this.notifyAll();
        return product;
    }
}

3、生產者

/**
 * 生產者
 * Created by hgg on 2019/9/29.
 */
public class Producter extends Thread {

    private ProductPool pool;

    public Producter(ProductPool pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        while (true){
            String name = (int)Math.random()*100+"號";
            System.out.println("生產了"+name);
            Product product = new Product(name);
            this.pool.push(product);
        }
    }
}

4、消費者

/**
 * 消費者
 * Created by hgg on 2019/9/29.
 */
public class Consumer extends Thread {
    private ProductPool pool;

    public Consumer(ProductPool pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        while (true){
            Product product = this.pool.pop();
            System.out.println("消費了:"+product.getName());
        }
    }
}

5、主程序入口

public class MainProgram {
    public static void main(String[] args) {
        ProductPool productPool = new ProductPool(15);
        
        new Producter(productPool).start();
        
        new Consumer(productPool).start();
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章