别的不多说,直接代码上:

package cn.thread.lock;
//主方法
public class ProducerCustomer {
    public static void main(String[] args) {
        Pool pool=new Pool();
        Customer c=new Customer(pool);
        Producer p=new Producer(pool);
        new Thread(c).start();
        new Thread(p).start();
        
        
    }
}
//产品类
class Product{
    int id;
    public Product(int id) {
        this.id=id;
    }
    @Override
    public String toString() {
        
        return "product:"+id;
    }
}
//池类
class Pool{
    private int index=0;
    private Product[] products=new Product[5];
    //生产
    public synchronized void push(Product p){
        while(index==products.length){//池子满了
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        products[index]=p;
        this.index++;
    }
    //消费
    public synchronized Product pop(){
        while(index==0){//池子空了
            try {
                this.wait();
            } catch (InterruptedException e) {
                
                e.printStackTrace();
            }
        }
        this.notify();
        index--;
        return products[index];
    }
    
    
}
//消费者
class Customer implements Runnable{
    private Pool pool=null;
    
    Customer(Pool p){
        this.pool=p;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            Product product = pool.pop();
            System.out.println("消费了:"+product);
        }
        try {
            Thread.sleep(1000);//消费一个产品,休眠1秒钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        
    }
    
}
//生产者
class Producer implements Runnable{
private Pool pool=null;
    
    Producer(Pool p){
        this.pool=p;
    }
    @Override
    public void run() {
        
        for (int i = 0; i < 20; i++) {
            Product product = new Product(i);
            pool.push(product);
            System.out.println("生产了产品:"+product);
            try {
                Thread.sleep(1000);//生产一个产品,休息1秒钟
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}

 

相关文章:

  • 2021-07-01
  • 2021-09-21
  • 2021-10-14
  • 2022-12-23
  • 2021-06-09
  • 2021-05-14
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-19
  • 2022-01-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-05
相关资源
相似解决方案