Java简单实现进程调度算法 FCFS和SJF

import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class experiment1 {
	public static void main(String[] args) {
		Scanner in= new Scanner(System.in); 
		
		System.out.println("请输入进程个数:");
		int n=in.nextInt();
		
		Process[] p=new Process[n];
		
		System.out.println("请输入每个进程的到达时间和服务时间和进程ID:");
		
		//初始化进程数据
		for(int i=0;i list,int now){
		Process pro=list.get(0);
		int index=0;
		for(int i=1;i 0 && target.arrivalTime < array[j - 1].arrivalTime)
	        {
	            array[j] = array[j - 1];
	            j--;
	        } 
	        array[j] = target;
	    }
	}
	
	//先来先服务算法
	public static void FCFS(Process[] p){
		
		//按到达时间对进程进行排序
		InsertSort(p);
				
		for(int i=0;ip[i-1].finishTime){
					p[i].finishTime=p[i].arrivalTime+p[i].serviceTime;
					p[i].startTime=p[i].arrivalTime;
				}
				else{
					p[i].finishTime=p[i].serviceTime+p[i-1].finishTime;
					p[i].startTime=p[i-1].finishTime;
				}
			}
			
			//计算周转时间和带权周转时间
			p[i].WholeTime=p[i].finishTime-p[i].arrivalTime;
			p[i].weightWholeTime=(double)p[i].WholeTime/(double)p[i].serviceTime;
			
		}
	}
	
	//短作业优先算法
	public static Process[] SJF(Process[] p){
		
		//当前时间
		int now=0;
		//待处理list
		List list=new LinkedList<>();
		//结果list
		List res=new LinkedList<>();
		//按时间对进程进行排序
		InsertSort(p);
		
		//处理第一个进程
		p[0].finishTime=p[0].arrivalTime+p[0].serviceTime;
		p[0].WholeTime=p[0].finishTime-p[0].arrivalTime;
		p[0].weightWholeTime=p[0].WholeTime/p[0].serviceTime;
		res.add(p[0]);
		
		now=p[0].finishTime;
		
		//将剩余进程添加进待处理list
		for(int i=1;inow){
				next.finishTime=next.arrivalTime+next.serviceTime;
				next.startTime=next.arrivalTime;
			}else{
				next.finishTime=now+next.serviceTime;
				next.startTime=now;
			}
			now=next.finishTime;
			next.WholeTime=next.finishTime-next.arrivalTime;
			next.weightWholeTime=(double)next.WholeTime/(double)next.serviceTime;
			res.add(next);
		}	
			
		return res.toArray(new Process[0]);
		
	}
	

}

//进程的数据结构
class Process{
	public int arrivalTime;
	public int serviceTime;
	public int finishTime;
	public int startTime;
	public int WholeTime;
	public double weightWholeTime;
	public String pid;
	
	Process(int x,int y,String id){
		arrivalTime=x;
		serviceTime=y;
		pid=id;
	}
}

Java简单实现进程调度算法 FCFS和SJF_第1张图片

你可能感兴趣的:(操作系统)