1 package com.company.osExperiment.algorithm; 2 3 import com.company.osExperiment.entity.PCB; 4 5 import java.util.ArrayList; 6 import java.util.List; 7 import java.util.Scanner; 8 9 import static com.company.osExperiment.entity.PCB.R; 10 import static com.company.osExperiment.util.ResultUtil.addResult; 11 12 /** 13 * 非抢占式,短作业优先调度算法 14 * @Author swsbty 15 * @Date 2020/6/9 4:31 16 */ 17 18 public class SJF { 19 20 private int current = 0; // 记录系统当前时间的变量 21 private List<PCB> processList; 22 23 /* 24 启动方法 25 */ 26 public void start() { 27 processList = new ArrayList<>(); 28 System.out.println("time 1=1000 time slice"); 29 addResult("time 1=1000 time slice"); 30 inputProcess(); 31 sort(); 32 run(); 33 } 34 35 /* 36 执行调度算法 37 */ 38 private void run() { 39 while (true) { 40 if (processList.size() == 0) { // 如果所有进程都执行完毕,就终止循环 41 return; 42 } 43 runProcess(); 44 } 45 } 46 47 /* 48 运行进程 49 */ 50 private void runProcess() { 51 for (PCB pcb : processList) { 52 if (pcb.state == R && pcb.arriveTime <= current) { // 如果进程没有执行完毕,同时到达时间小于等于当前时间 53 System.out.println("当前时间:" + (current * 1000) + ",进程" + pcb.name + " 开始运行"); 54 addResult("当前时间:" + (current * 1000) + ",进程" + pcb.name + " 开始运行"); 55 current += pcb.runtime; // 当前时间加上运行时间 56 System.out.println("当前时间:" + (current * 1000) + ",进程" + pcb.name + " 运行结束"); 57 addResult("当前时间:" + (current * 1000) + ",进程" + pcb.name + " 运行结束"); 58 processList.remove(pcb); // 删除该进程 59 break; 60 } 61 } 62 } 63 64 /* 65 录入进程 66 */ 67 private void inputProcess() { 68 int num; // 要建立的进程数 69 System.out.print("你想运行多少个进程:"); 70 addResult("你想运行多少个进程:"); 71 72 Scanner input = new Scanner(System.in); 73 num = input.nextInt(); 74 addResult("" + num); 75 for (int i = 0;i < num;i++) { 76 PCB p = new PCB(); 77 System.out.print(String.format("请输入第 %3d 个进程的名字:", i + 1)); 78 addResult(String.format("请输入第 %3d 个进程的名字:", i + 1)); 79 p.name = input.next(); 80 addResult(p.name); 81 82 System.out.print(" 运行时间:"); 83 addResult(" 运行时间:"); 84 p.runtime = input.nextInt(); 85 addResult("" + p.runtime); 86 87 System.out.print(" 到达时间:"); 88 addResult(" 到达时间:"); 89 p.arriveTime = input.nextInt(); 90 addResult("" + p.arriveTime); 91 92 93 p.state = R; 94 processList.add(p); 95 } 96 } 97 98 /* 99 ☆选择排序 100 该算法把录入的进程,按照运行时间,由小到大排序 101 */ 102 private void sort() { 103 for (int i = 0;i < processList.size() - 1;i++) { 104 for (int j = i + 1;j < processList.size();j++) { 105 if (processList.get(i).runtime > processList.get(j).runtime) { 106 PCB pi = processList.get(i); 107 PCB pj = processList.get(j); 108 processList.set(i, pj); 109 processList.set(j, pi); 110 } 111 } 112 } 113 } 114 }