JavaNote 2.9线程生产消费问题实例

本文介绍了一个使用Java实现的仓库管理案例,通过两个线程分别模拟苹果的采集与销售过程,并利用synchronized关键字来确保线程安全。初始时仓库中有50个苹果,采集线程会在仓库苹果数量少于100时进行采集操作,而销售线程则在有苹果的情况下进行销售。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类1

public class Cangku {

    public static int num = 50;
    private String name;
    Cangku(String name){
        this.name = name;
    }
    public synchronized void cai(){
        while (num == 100){
            try {
                this.wait();
                notify();
            }
            catch (InterruptedException e){
                e.getStackTrace();
            }

        }
        for(int i = 1;i<=(100-num);i++){
            System.out.println("正在采集一个苹果");
            num++;
            System.out.println("目前仓库拥有苹果"+ num +"个");
        }
    }
    public synchronized void mai(){
        while (num==0){
            try {
                this.wait();
                this.notify();
            }
            catch (InterruptedException e){
                e.getMessage();
            }
        }
        for(int i = 1;i<=num;i++){
            System.out.println("正在销售一个苹果");
            num--;
            System.out.println("目前仓库拥有苹果"+ num +"个");
        }
    }
}

类2
public class Test5 implements Runnable{
    private Cangku cangku;
    Test5(Cangku cangku){
        this.cangku = cangku;
    }
    @Override
    public void run() {
            cangku.cai();
    }
}
类3
public class Test6 implements Runnable {
    private Cangku cangku;
    Test6(Cangku cangku){
        this.cangku = cangku;
    }
    @Override
    public void run() {
            cangku.mai();
    }
}
类4
public class Test7 {
    public static void main(String args[]){
        Cangku cangku = new Cangku("苹果仓库");
        Thread thread = new Thread(new Test5(cangku),"采集线程");
        thread.start();
        Thread thread1 = new Thread(new Test6(cangku),"销售线程");
        thread1.start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值