JAVAマルチスレッド(1)単純なプロデューサーとコンシューマー

//仓库代码
public class Depot {

    private int capacity;
    private int size=0;

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

    public synchronized void product(int count) throws InterruptedException {
        while(count>0){
            if(size>capacity){
                wait();
            }
            //真实的生产数量
            int realCount=(capacity-size)>=count?count:(capacity-size);
            System.out.print(Thread.currentThread().getName()+"--本次想要生产:"+count+",本次实际生产:"+realCount);
            //下次生产数量
            count=count-realCount;
            //仓库剩余
            size+=realCount;
            System.out.println(",下次想要生产:"+count+",仓库真实容量:"+size);
            notifyAll();
        }
    }

    public synchronized void comsume(int count) throws InterruptedException {
        while (count>0){
            if(size<=0){
                wait();
            }
            
            //真实消费数量
            int realCount=(size>count)?count:size;
            System.out.print(Thread.currentThread().getName()+"--本次想要消费:"+count+",本次真实消费:"+realCount);
            //下次消费
            count=count-realCount;
            //仓库剩余
            size-=realCount;
            System.out.println("下次想要消费:"+count+",仓库剩余:"+size);
            notify();
        }
    }



}

 

//生产者
public class Product {

    Depot depot;

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

    public void produce(final int count){
        new Thread() {
            public void  run(){
                try {
                    depot.product(count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
//消费者
public class Comsumer {

    Depot depot;

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

    public void  comsumers(final  int count){
        new Thread(new Runnable() {
            @Override
            public void run() {
                    try {
                        depot.comsume(count);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        }){
        }.start();

    }

}

 

 

//测试
public class TestThread {

    public static void main(String[] args) {

        Depot depot=new Depot(100);

        Product product=new Product(depot);
        Comsumer comsumer=new Comsumer(depot);

        product.produce(20);
        product.produce(30);
        product.produce(20);

        comsumer.comsumers(40);
        comsumer.comsumers(20);

        product.produce(30);

        comsumer.comsumers(20);
    }


}

 

おすすめ

転載: blog.csdn.net/qq_37203082/article/details/112317958