java实现银行家算法

public class BankerArithmetic {
    private int Possess[];// 系统拥有的资源向量
    private int Available[];// 可用资源向量
    private int Max[][];// 最大需求矩阵
    private int Allocation[][];// 分配矩阵
    private int Need[][];// 需求矩阵
    private int[] safeSequence;// 保存安全序列
    private Map<Integer,String> map = new HashMap<Integer,String>();//存放等待的进程
    public static void main(String[] args) {


        BankerArithmetic test = new BankerArithmetic();
// 初始化 并显示
        test.Init();
        test.show();
        System.out.println("**********");
// 该时刻状态安全
        if(test.isSafe(test.Available))
        {
            test.safeSequence();
        }
        else
        {
            System.out.println("该时刻为不安全状态");
        }
        System.out.println("**********");
// 循环进行分配
        int inProcess;
        int choice ;
        int[] inputRequest = new int[test.Max[0].length];
        while (true)
        {
            Scanner s = new Scanner(System.in);
            System.out.println("请选择:\n0(退出)\n1(请求分配)\n2(初始化)");
            choice = s.nextInt();
            if (choice==0)
                break;
            else if(choice==2)
            {
                test.Init();
                test.show();
            }
            System.out.println("请输入要请求的进程号(0--" + test.Max.length + "):");
            inProcess = s.nextInt();
            System.out.println("请输入请求的资源数目:");
            for (int i = 0; i < 3; i++) {
                System.out.print("Request[" + i + "]=");
                inputRequest[i] = s.nextInt();
            }
            System.out.print("Request:");
            for(int request:inputRequest)
                System.out.print(request+"  ");
            test.request(inProcess, inputRequest);
            test.show();
            test.showWaitingProcess();
            System.out.println("**********");
        }
    }


    /**
     * 初始化Max,Allocation,Need,Possess,Available
     */
    private void Init() {
/**
 * max:
 * 5,5,9 
 * 4,3,6
 * 4,0,11
 * 4,2,5
 * 4,2,4
 * */
        Max = new int[][] { { 5, 5, 9 }, { 5, 3, 6 }, { 4, 0, 11 },
                { 4, 2, 5 }, { 4, 2, 4 } };
/**
 * Allocation:
 * 2,1,2 
 * 4,0,2 
 * 4,0,5 
 * 2,0,4 
 * 3,1,4
 * */
        Allocation = new int[][] { { 2, 1, 2 }, { 4, 0, 2 }, { 4, 0, 5 },
                { 2, 0, 4 }, { 3, 1, 4 } };


/**
 * Need Need[i][j]=Max[i][j]-Allocation[i][j];
 */
        Need = new int[Max.length][Max[0].length];
        for (int i = 0; i < Max.length; i++) {
            for (int j = 0; j < Max[0].length; j++) {
                Need[i][j] = Max[i][j] - Allocation[i][j];
            }
        }
/**
 * 系统资源总和
 * */
        Possess = new int[] { 17, 5, 20 };

/**
 * Available[i] = Posses[i]-Allocation[i];
 *
 * */
        Available = new int[Possess.length];
        for (int j = 0; j < Max[0].length; j++) {
            int countAllocation = 0;
            for (int i = 0; i < Max.length; i++) {
                countAllocation += Allocation[i][j];
            }


            Available[j] = Possess[j] - countAllocation;
        }
    }
    /**显示
     * Max,Allocation,Need,
     * 系统现有进程
     * Possess,Available
     */
    public void show() {
        System.out.println("Max[][]    Allocatio[][]    Need[][]");
        for (int i = 0; i < Max.length; i++) {
            for (int j = 0; j < Max[0].length; j++) {
                System.out.print(Max[i][j] + "  ");
            }
            System.out.print("     ");
            for (int j = 0; j < Max[0].length; j++) {
                System.out.print(Allocation[i][j] + "  ");
            }
            System.out.print("     ");
            for (int j = 0; j < Max[0].length; j++) {
                System.out.print(Need[i][j] + "  ");
            }
            System.out.println();
        }
        System.out.print("系统现有进程:");
        for (int i = 0; i < Max.length; i++) {
            System.out.print("P" + i + "  ");
        }
        System.out.print("\n系统拥有资源:");
        for (int i = 0; i < Max[0].length; i++) {
            System.out.print(Possess[i] + "   ");
        }
        System.out.print("\n系统可用资源:");
        for (int i = 0; i < Max[0].length; i++) {
            System.out.print(Available[i] + "    ");
        }
        System.out.println();
    }

    /**
     * 判断系统是否安全.若果安全则返回true
     * @param tempAvailable:可用资源
     * @return
     */
    private boolean isSafe(int[] tempAvailable) {
/**
 *  工作向量初始值等于Available[]
 *
 *  注意如果 将 Work=tempAvailable;会出错 ,地址传递会改变Available的内容
 *  此处为引用传递
 *  区别值传递与引用传递的机制
 */
        int[] Work = new int[Max[0].length];
// 初始值全为false
        boolean[] Finish = new boolean[Max.length];
//temp的值表示安全序列
        int temp = 0;
//k:安全序列的下标
        int k = 0;
//判断是否安全
        boolean safe = true;
        safeSequence = new int[Max.length];
        for (int j = 0; j < Max[0].length; j++) {
            Work[j] = tempAvailable[j];//tempAvailable 不随 Work的改变而改变;
        }
        while (temp < Max.length) {
            if (Finish[temp] == false && Need[temp][0] <= Work[0]
                    && Need[temp][1] <= Work[1] && Need[temp][2] <= Work[2]) {
                for (int i = 0; i < Max[0].length; i++) {
                    Work[i] += Allocation[temp][i];
                    Finish[temp] = true;
                }
                safeSequence[k] = temp;
                k++;
                temp = 0;
            } else {
                temp++;
            }
        }
        for (int i = 0; i < Max.length; i++) {
            safe&=Finish[i];
        }
        return safe;
    }
    /**
     * 提出申请,判断是否分配。若分配后为安全状态,则允许,否则,拒绝分配。
     * @param process  代表进程
     * @param request代表进程申请各资源数组成的集合
     */
    private void request(int process, int[] request) {
        boolean isOK = true;
/**
 *  如果请求Request[i]<=Available&&Request[i]<=Need[i]
 *  则分配资源,对修改后的数据执行安全算法,若该时刻系统安全,则分配完成
 *  否则,撤销之前的资源分配
 */
        String str="P"+process+":";
        for(int req:request)
        {
            str+=req+",";
        }
        for (int i = 0; i < Max[0].length; i++) {
            isOK &= (request[i] <= Available[i]);
            if(!isOK)
            {
                System.out.println("\n请求资源数超过可用资源数,P"+process+"等待");
                map.put(i, str);
                return;
            }
            isOK &= (request[i] <= Need[process][i]);
            if(!isOK)
            {
                System.out.println("\n请求资源数超过还需要的资源数,P"+process+"请求错误");
                return;
            }
        }
//isOK=true  满足分配
        if (isOK) {
//分配资源
            for (int i = 0; i < Max[0].length; i++) {
                Available[i] -= request[i];
                Allocation[process][i] += request[i];
                Need[process][i] -= request[i];
            }
            if (isSafe(Available)) {
                System.out.println("\n条件满足,P" + process + "申请成功");
                safeSequence();
            } else
            {//撤销分配
                for (int i = 0; i < Max[0].length; i++) {
                    Available[i] += request[i];
                    Allocation[process][i] -= request[i];
                    Need[process][i] += request[i];
                }
                System.out.println("\n分配后为不安全状态。撤销分配");
            }
        }
    }

    //若该时刻安全则输出安全序列
    public void safeSequence()
    {
        System.out.print("该时刻安全,safe sequence is:");
        for (int safeTemp : safeSequence) {
            System.out.print("P" + safeTemp + "->");
        }
        System.out.println();
    }
    //显示等待的进程申请
    public void showWaitingProcess()
    {
        if(map==null)
        {
            System.out.println("当前无等待的进程");
            return;
        }
        System.out.println("当前等待的进程申请:");
        for (Integer Key : map.keySet())
        {
            System.out.println(map.get(Key)+" ");
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值