模拟一个人生产50个玩具,每200毫秒生产一个,当生产到第20个时加入每秒吃1个馒头,共吃完3个后在接着生产的多线程。

package com.lianxi.thread;

/**
 * 模拟一个人生产50个玩具,每200毫秒生产一个,当生产到第20个时加入每秒吃1个馒头,共吃完3个后在接着生产的多线程。
 */

public class Person2 {
    int toy=0;
    int steamedbun=1;
    public synchronized void ManufactureToys(){//使用 synchronized 保证线程安全
        while (toy<50){//当其他线程调用 notify 通知时,继续生产玩具,直到生产达到50个为止。
            toy++;
            System.out.println(Thread.currentThread().getName()+"生产的第"+toy+"个玩具");
            if (toy==20){//当玩具数量达到20时,线程会进入等待状态,同时释放锁,允许其他线程执行
                System.out.println("生产到第"+toy+"个玩具,开始吃馒头");
                try {
                    wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            notify();
        }
    }
    public synchronized void EatsteamedBun(){
        while (steamedbun<=3){
            System.out.println(Thread.currentThread().getName()+"吃第"+steamedbun+"个馒头");
            if(steamedbun==3){
                try {
                    wait();//在吃到第3个馒头时,线程会进入等待状态,释放锁,等待其他线程的通知。
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                break;
            }else {
                steamedbun++;
            }
            notify();
        }
    }
}
class Produc extends Thread{
    private Person2 person2;
    public Produc(Person2 person2){
        this.person2=person2;
    }

    @Override
    public void run() {
        try {
            sleep(200);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        person2.ManufactureToys();
    }
}
class Eat extends Thread{//吃馒头的分线程
    private Person2 person2;
    public Eat(Person2 person2){
        this.person2=person2;
    }

    @Override
    public void run() {
        try{
            sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        person2.EatsteamedBun();
    }
}
class PersonTest{//分别启动两个线程。这样,生产者和消费者可以并发执行,模拟了玩具的生产和馒头的消费过程。
    public static void main(String[] args){
        Person2 p=new Person2();
        Produc p1=new Produc(p);
        Eat e=new Eat(p);
        p1.setName("一号生产人员");
        e.setName("一号生产人员");
        e.start();
        p1.start();
    }
}
  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值