- 银行家算法的基本原理
- 代码实现
- 测试结果截图
操作系统死锁避免——银行家算法
2. 代码实现 1). 资源分配表类 (SrcAllocTable) 与进程记录类 (Record)public class SrcAllocTable {
private int processNum;
private int sourceNum;
private Record[] table;
private int[] sum;
private int[] available;
public SrcAllocTable(int[] sum, Record[] table) {
// if(sum.length != table.length)
// throw XXXException;
this.sum = sum;
this.table = table;
this.processNum = table.length;
this.sourceNum = sum.length;
this.available = sum.clone();
for(int i = 0; i
2). 银行家类(实现银行家算法)
public class Banker {
private SrcAllocTable srcTable;
public Banker(SrcAllocTable table) {
this.srcTable = table;
}
public boolean securityDetect(int i, int[] request) {
boolean isSecurity = false;
// 先复制整张资源分配表
SrcAllocTable tmpTable = new SrcAllocTable(srcTable);
showDebugInfo("Before allocation: ", tmpTable);
// 1. 试探性分配资源
Record[] table = tmpTable.getTable();
int[] need = table[i].getNeed();
int[] available = tmpTable.getAvailable();
int[] allocated = table[i].getAllocation();
for (int k = 0; k < request.length; k++) {
need[k] -= request[k];
available[k] -= request[k];
allocated[k] += request[k];
}
showDebugInfo("After allocation: ", tmpTable);
int procCount = 0;
StringBuilder procQueue = new StringBuilder();
int procNum = tmpTable.getProcessNum(); // 尚未完成的进程或者说表中 isFinished 为 false 的记录的数量
int srcNum = tmpTable.getSourceNum(); // 资源种类数
for(int n = 0; n need[k] || request[k] > available[k]) {
System.out.println("Sorry, the requested source may out of needed or available source!");
return false;
}
// 3. security Detect
return securityDetect(i, request);
}
// 打印资源分配表的情况
public void showDebugInfo(String info, SrcAllocTable tmpTable){
System.out.println(info);
System.out.println(tmpTable);
System.out.println("------------------------------------------");
}
public static void main(String[] args) {
int[] max0 = {7, 5, 3};
int[] allocation0 = {0, 1, 0};
Record r0 = new Record("p0", max0, allocation0);
int[] max1 = {3, 2, 2};
int[] allocation1 = {2, 0, 0};
Record r1 = new Record("p1", max1, allocation1);
int[] max2 = {9, 0, 2};
int[] allocation2 = {3, 0, 2};
Record r2 = new Record("p2", max2, allocation2);
int[] max3 = {2, 2, 2};
int[] allocation3 = {2, 1, 1};
Record r3 = new Record("p3", max3, allocation3);
int[] max4 = {4, 3, 3};
int[] allocation4 = {0, 0, 2};
Record r4 = new Record("p4", max4, allocation4);
Record[] table = {r0, r1, r2, r3, r4};
int[] sum = {10, 5, 7};
SrcAllocTable st = new SrcAllocTable(sum, table);
System.out.println(st);
// Banker
Banker banker = new Banker(st);
int i = 1;
int[] request = {1, 0, 2};
System.out.println(banker.ifAllocate(i, request));
}
}
3. 测试结果:



