package xyh.os.process;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
/**
* @author XiangYida
* @version 2018/12/6 14:14
* 优先权法
*/
class PCB implements Comparable<PCB>{
public int id;
public int pre;
public int time;
public String state;
public PCB(){};
public PCB(int id, int pre, int time, String state) {
this.id = id;
this.pre = pre;
this.time = time;
this.state = state;
}
public void show(){
System.out.println("进程ID:"+id+" 进程优先级:"+pre+" 进程所需时间片"+time+" 进程状态"+state);
}
@Override
public int compareTo(PCB o) {
return o.pre-this.pre;
}
}
public class Test01 {
private static int time=200;
public static void main(String[] args) throws InterruptedException {
LinkedList<PCB>list=new LinkedList<>();
list.add(new PCB(1,30,8,"ready"));
list.add(new PCB(2,10,9,"ready"));
list.add(new PCB(3,24,4,"ready"));
list.add(new PCB(4,19,10,"ready"));
list.add(new PCB(5,11,12,"ready"));
Scanner scanner=new Scanner(System.in);
int i=scanner.nextInt();
if(i==1)m1(list);
else m2(list);
}
public static void m1(LinkedList<PCB> list) throws InterruptedException {
System.out.println("**********优先权法**********");
System.out.println("=========当前CPU时间片:"+time+" =========");
Collections.sort(list);
while (!list.isEmpty()&&time>0){
PCB pcb=list.peek();
pcb.pre-=1;
pcb.time-=3;
pcb.state="running";
time-=3;
if(pcb.time<=0){
System.out.println("撤销进程:"+pcb.id+" 且该进程的状态为:finish");
list.pop();
Collections.sort(list);
}
Thread.sleep(1000);
System.out.println("队列中进程状态");
for(PCB pcb1:list){
pcb1.show();
}
System.out.println("=================================================");
}
if(time<=0) System.out.println("========时间片完========");
else System.out.println("所有进程执行完毕");
}
public static void m2(LinkedList<PCB> list) throws InterruptedException {
System.out.println("**********轮转法**********");
System.out.println("=========当前CPU时间片:"+time+" =========");
while (!list.isEmpty()&&time>0){
PCB pcb=list.peek();
pcb.pre-=1;
pcb.time-=3;
pcb.state="running";
time-=3;
if(pcb.time<=0){
System.out.println("撤销进程:"+pcb.id+" 且该进程的状态为:finish");
list.pop();
}
Thread.sleep(1000);
System.out.println("队列中进程状态");
for(PCB pcb1:list){
pcb1.show();
}
System.out.println("=================================================");
}
if(time<=0) System.out.println("========时间片完========");
else System.out.println("所有进程执行完毕");
}
}
进程同步-优先权法与轮转法
最新推荐文章于 2021-05-30 14:24:27 发布