先来先服务(FCFS)与最短作业优先(SJF)
设计思路:
先来先服务(FCFS)调度算法是按照作业到达的先后次序来进行调度,而不管该作业所需执行时间的长短,从后备队列中选择几个最先进入该队列的作业,将他们调入内存进行调度。即当一个程序在运行时,后面有一个进程在后面进来,则在当前运行的进程先服务完再调度服务后面一个进程。这次实验主要用链表完成,首先把全部进程的名称、到达时刻、服务时间输进一个链表,然后对链表中的进程按照到达时刻按从小到大的顺序进行排序,然后对链表中进程一个接着一个进行处理。
最短作业优先(SJF)调度算法是根据进程的服务时间长短进行调度,当只有一个进程时系统直接处理这个进程。当系统中有多个进程时,最先到达的一个进程先服务完,后面的进来的进程则按照服务之间的长短按从小到大进行排序,然后对链表中的进程进行处理。
import java.util.Scanner;
public class FirstInFirstOut {
private static int pNumber;
static Process H=null;
static Process L=H;
public static void main(String[] args) {
System.out.println("请输入进程数:");
Scanner p=new Scanner(System.in);
pNumber=p.nextInt();
String pName;
int arriveTime;
int serviceTime;
for(int i=0;i<pNumber;i++) {
System.out.println("请输入第"+(i+1)+"个进程(进程名 到达时间 服务时间):");
pName=p.next();
arriveTime=p.nextInt();
serviceTime=p.nextInt();
addProcess(pName,arriveTime,serviceTime);
}
arriveSort();
dealProcess();
printProcess();
System.out.println("----------------------------------");
arriveSort();
serviceSort();
dealProcess();
printProcess();
}
public static void addProcess(String pName,int arriveTime,int serviceTime) {//插入进程
Process p=new Process(pName,arriveTime,serviceTime);
if(H==null) {
H=p;
}else {
L.next=p;
}
L=p;
}
public static void dealProcess() {//处理进程
Process deal=H;
int time=H.arriveTime;
while(deal!=null) {
if(deal.arriveTime>time) {
deal.startTime=deal.arriveTime;
}else {
deal.startTime=time;
}
deal.completeTime=deal.serviceTime+deal.startTime;
deal.allTime=deal.completeTime-deal.arriveTime;
time=deal.completeTime;
deal=deal.next;
}
}
public static void arriveSort() {//到达时间排序
int t,s;
String n;
Process as1=H;
Process as2=H;
while(as1!=null) {
while(as2!=null) {
if(as1.arriveTime>as2.arriveTime) {
s=as1.serviceTime;
as1.serviceTime=as2.serviceTime;
as2.serviceTime=s;
n=as1.pName;
as1.pName=as2.pName;
as2.pName=n;
t=as1.arriveTime;
as1.arriveTime=as2.arriveTime;
as2.arriveTime=t;
}
as2=as2.next;
}
as1=as1.next;
if(as1!=null) {
as2=as1.next;
}
}
}
public static void serviceSort() {//服务时间排序
int t,s;
String n;
Process as1=H.next;
Process as2=H.next;
while(as1!=null) {
while(as2!=null) {
if(as1.serviceTime>as2.serviceTime) {
s=as1.serviceTime;
as1.serviceTime=as2.serviceTime;
as2.serviceTime=s;
n=as1.pName;
as1.pName=as2.pName;
as2.pName=n;
t=as1.arriveTime;
as1.arriveTime=as2.arriveTime;
as2.arriveTime=t;
}
as2=as2.next;
}
as1=as1.next;
if(as1!=null) {
as2=as1.next;
}
}
}
public static void printProcess() {
Process c=H;
System.out.println("进程调度信息信息如下:");
System.out.println("进程名称\t到达时刻\t服务时间\t开始时刻\t完成时间\t周转时间\t");
while(c!=null) {
System.out.println(c.pName+"\t"+c.arriveTime+"\t"+c.serviceTime+"\t"+c.startTime+"\t"+c.completeTime+"\t"+c.allTime+"");
c=c.next;
}
}
static class Process {//进程节点信息
String pName;
int arriveTime;
int serviceTime;
int startTime;
int completeTime;
int allTime;
Process next;
Process(String pName, int arriveTime, int serviceTime) {
super();
this.pName = pName;
this.arriveTime = arriveTime;
this.serviceTime = serviceTime;
}
}
}