2021-3-7保融科技java编程题

第一题是给出好几个设计模式选一个举例子实现,当时是想到了一个婚庆公司代理结婚的代理模式样例,但没有实现。

第二题是生产者消费者模型的问题,我记得题目大概是:
蛋糕制作者负责生产蛋糕,会将生产的蛋糕放在一个桌子,桌子最多能放3个蛋糕,满了就得等顾客来吃,顾客负责在桌子上拿蛋糕吃,桌子上没有就只能等。

以下是我的实现方式:

1.定义桌子类 Table

public class Table {
    
    
    // 能够存放的蛋糕最大数量为3
    final static int capacity = 3;
    // 蛋糕数量
    int cake;
}

2.定义蛋糕制造者类 CakeMaker

class CakeMaker implements Runnable{
    
    
    private Table table;
    CakeMaker(Table table){
    
    
        this.table = table;
    }
    @Override
    public void run() {
    
    
        while (true){
    
    
            try {
    
    
                synchronized (table){
    
    
                    // 如果桌子上还有空位放蛋糕,则添加蛋糕
                    if(table.cake < Table.capacity){
    
    
                        table.cake ++;
                        System.out.println("蛋糕制造者生产了一个蛋糕,现在还有"+table.cake+"个蛋糕");
                    }
                }
                //延时一会会
                Thread.sleep(1300);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

3.定义顾客类Customer

class Customer implements  Runnable{
    
    
    Table table;
    Customer(Table table){
    
    
        this.table = table;
    }
    @Override
    public void run() {
    
    
        while (true){
    
    
            try {
    
    
                synchronized (table){
    
    
                    while (table.cake > 0){
    
    
                        table.cake--;
                        System.out.println("顾客吃了一个蛋糕,现在还有"+table.cake+"个蛋糕");
                    }
                }
                Thread.sleep(2000);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

4.测试

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Table table = new Table();
        CakeMaker cakeMaker = new CakeMaker(table);
        Customer customer = new Customer(table);
        new Thread(cakeMaker).start();
        new Thread(customer).start();
    }

}

5.测试结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44099545/article/details/114602128
今日推荐