银行家算法的java编程实现

主程序:

import java.util.*;

public class BankManager {
	public static void main(String[] args){
		Scanner scanner=new Scanner(System.in);
		TheBanker tb = new TheBanker();
		tb.deadlockAvoidance();//死锁避免
		int gate = 1;
		while(gate!=0){ 
			tb.deadlockDetection();//死锁检测
			System.out.println("如果您要继续分配资源请输入\"1\",退出请输入\"0\"");
			System.out.print("您输入的值为:");
			gate = scanner.nextInt();
			System.out.println();
		}
		System.out.println("使用愉快!期待您下次使用!");
	}
}

银行家算法主要实现:

import java.util.Scanner;

public class TheBanker {
	int m;
	int n;
	int[][] max;
	int[][] maxbak;
	int[][] allocation;
	int[][] allocationbak;
	int[][] need;
	int[][] needbak;
	int[] available;
	int[] availablebak;
	
	public TheBanker(){
		Scanner s=new Scanner(System.in);
		System.out.println("初始化中……");
		System.out.println("请输入系统中的【进程数】和【资源数】");
		m=s.nextInt();
		n=s.nextInt();
		max=new int[m][n];
		maxbak=new int[m][n];
		allocation=new int[m][n];
		allocation=new int[m][n];
		need=new int[m][n];
		needbak=new int[m][n];
		available=new int[n];
		availablebak=new int[n];
		for(int i=0;i9){
					System.out.print(max[i][j]+" ");
				}else{
					System.out.print(" "+max[i][j]+" ");
				}
			}
			System.out.println(" ");
			for(int j=0;j9){
					System.out.print(allocation[i][j]+" ");
				}else{
					System.out.print(" "+allocation[i][j]+" ");
				}
			}
			if(i==0){
				System.out.print(" ");
				for(int j=0;j9){
						System.out.print(available[j]+" ");
					}else{
						System.out.print(" "+available[j]+" ");
					}
				}
			}
			System.out.println();
		}
		System.out.println("======完成初始化======");
		System.out.println();
	}
	
	public void deadlockAvoidance(){
		int[] security=new int[m];
		int[] tar=new int[n];
		boolean[] param=new boolean[m];
		int count=0;
		int num1=m+1;
		int num2=m;
		
		while(num1>0){
			for(int i=0;i0)){
				System.out.println("【安全序列为:】");
				for(int i=0;i");
					}
				}
				System.out.println();
				System.out.println("=====【死锁避免】结束=====");
				System.out.println();
				return;
			}
		}
	}
	
	public void deadlockDetection(){
		Scanner scanner=new Scanner(System.in);
		int key;
		int[] security=new int[m];
		boolean[] param=new boolean[m];
		int[] temp=new int[n];
		int[] tar=new int[n];
		int count=0;
		int num1=m+1;
		int num2=m;
		for(int i=0;i0){
			for(int i=0;i1)){
				System.out.println("【安全序列】为:");
				for(int i=0;i");
					}
				}
				System.out.println();
				System.out.println("可以产生新的安全序列!系统能将资源分配给P"+key+"!");
				System.out.println("死锁检测结束。");
				System.out.println();
				return;
			}
			while((num2==0)&&(num1>1)){
				System.out.println("抱歉不能产生安全序列,系统无法分配资源。");
				System.out.println("系统不能将资源分配给P"+key+"!");
				System.out.println("死锁检测结束。");
				System.out.println();
				return;
			}
		}
	}
}


你可能感兴趣的:(银行家算法的java编程实现)