public static void main(String[] args) {
MyQueue myqueue = new MyQueue();//聲明隊列
PCB[] pcb = {new PCB(001,8,1),new PCB(002,7,9),new PCB(003,3,8),new PCB(004,1,7),new PCB(005,7,4)};
PCB para = new PCB();
for(int i=0;i<pcb.length;i++){//初始化後首先執行壹次排序,這裏使用的是選擇排序,優先級高的先入隊
for(int j=i;j<pcb.length;j++){
if(pcb[i].privilege < pcb[j].privilege){
para = pcb[i];
pcb[i] = pcb[j];
pcb[j] = para;
}
}
}
System.out.println("初次入隊後各進程的順序:");
for(int i=0;i<pcb.length;i++){
System.out.println("初次入隊後 # processname : " + pcb[i].name + " totaltime : " + pcb[i].totaltime + " privilege :" + pcb[i].privilege);
}
System.out.println();
myqueue.start(pcb);
}
}
class MyQueue {
int index = 0;
PCB[] pc = new PCB[5];
PCB[] pc1 = new PCB[4];
PCB temp = new PCB();
public void enQueue(PCB process){//入隊算法
if(index==5){
System.out.println("out of bounds !");
return;
}
pc[index] = process;
index++;
}
public PCB deQueue(){//出隊算法
if(index==0)
return null;
for(int i=0;i<pc1.length;i++){
pc1[i] = pc[i+1];
}
index--;
temp = pc[0];
for(int i=0;i<pc1.length;i++){
pc[i] = pc1[i];
}
return temp;
}
public void start(PCB[] pc){//顯示進程表算法
while(pc[0].isNotFinish==true||pc[1].isNotFinish==true||pc[2].isNotFinish==true||pc[3].isNotFinish==true||pc[4].isNotFinish==true){
//*註意:||運算符,所有表達式都為false結果才為false,否則為true
for(int i=0;i<pc.length;i++){
pc[i].run(this);
}
System.out.println();
for(int i=0;i<pc.length;i++){//所有進程每執行完壹次時間片長度的運行就重新按優先級排列壹次
for(int j=i;j<pc.length;j++){
if(pc[i].privilege < pc[j].privilege){
temp = pc[i];
pc[i] = pc[j];
pc[j] = temp;
}
}
}
}
}
}
class PCB {//聲明進程類
int name,totaltime,runtime,privilege;
boolean isNotFinish;
public PCB(){
}
public PCB(int name, int totaltime, int privilege){
this.name = name;//進程名
this.totaltime = totaltime;//總時間
this.privilege = privilege;//優先級別
this.runtime = 2;//時間片,這裏設值為2
this.isNotFinish = true;//是否執行完畢
System.out.println("初始值: processname : " + name + " totaltime : " + totaltime + " privilege :" + privilege );
System.out.println();
}
public void run (MyQueue mq){//進程的基於時間片的執行算法
if(totaltime>1){
totaltime-=runtime;//在總時間大於1的時候,總時間=總時間-時間片
privilege--;
System.out.println(" processname : " + name + " remaintime : " + totaltime + " privilege :" + privilege );
}else if(totaltime==1){
totaltime--;//在總時間為1時,執行時間為1
privilege--;
System.out.println(" processname : " + name + " remaintime : " + totaltime + " privilege :" + privilege );
}else{
isNotFinish = false;//總時間為0,將isNotFinish標記置為false
}
if(isNotFinish==true){
mq.deQueue();
mq.enQueue(this);
}
}
}