线程同步示例

描述:父亲和儿子共享一个盘子,父亲放苹果,儿子吃苹果,盘子里面只能放一个,父亲放苹果的时候,儿子不能吃,儿子取的时候,父亲不能放,盘子只放一个苹果,完成两个线程的同步问题
注:synchronized修饰的非静态方法是对象锁,静态方法是类锁

//盘子
class Dish{
    int apple =0;
    public synchronized void add() throws Exception{

        while(apple==1){
            this.wait();
        }
        if(apple==0){
            System.out.println("putting");
            apple=1;
            Thread.sleep(1000);
        }
        this.notify();
    }

    public synchronized void reduce()throws Exception{

        while(apple == 0){

            this.wait();
        }
        if(apple == 1){
            System.out.println("eatting");
            apple=0;
            this.notify();
        }
    }
}

class Father extends Thread{

    private Dish dish;

    public Father(Dish dish){
        this.dish = dish;
    }

    public void run(){
        while(true){
            try {
                dish.add();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

class Son extends Thread{

    private Dish dish;

    public Son(Dish dish){
        this.dish = dish;
    }

    public void run(){
        while(true){
            try {
                dish.reduce();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
public class apple {

    public static void main(String[] args) {
        Dish dish = new Dish();
        Father father = new Father(dish);
        Son son = new Son(dish);
        father.start();
        son.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值