第一步:创建一个found类
import java.util.ArrayList;
class Found {
ArrayList<PCB> sequnce;//创建就绪队列
PCB pcb[] = new PCB[5];
int StartTime = 0;
int SystemTime = (int) (Math.random() * 3) + 1;//随即产生系统时间
Found() {
sequnce = new ArrayList<PCB>();
for (int i = 0; i < 5; i++) {
pcb[i] = new PCB();
pcb[i].Id = i + 1;
sequnce.add(pcb[i]);
}
}
void FCFS()//先来先服务算法
{
PCB Running = null;
while (sequnce.size() > 0)//就绪队列不为空
{
Running = sequnce.remove(0);
Running.UseTime = Running.NeedTime;
Running.NeedTime = 0;
Running.Perior = 0;
System.out.println("当前系统时间:" + SystemTime);
SystemTime += Running.UseTime;
ShowMessages(Running);
}
}
void RR()//时间片轮换算法
{
PCB Running = null;
int Time = SystemTime;
while (sequnce.size() > 0) {
System.out.println("当前系统时间:" + SystemTime);
Running = sequnce.remove(0);
if (Running.NeedTime <= Time) {
Running.UseTime = Running.NeedTime;
Running.NeedTime = 0;
Running.Perior = 0;
Running.Status = "Finish";
SystemTime += Running.UseTime;
} else {
Running.UseTime += Time;
Running.NeedTime -= Time;
Running.Perior--;
Running.Status = "Ready";
sequnce.add(Running);
SystemTime += Time;
}
ShowMessages(Running);
}
}
void ShowMessages(PCB p)
//输出信息
{
System.out.println("当前运行进程:" + p.Id +
" " + "服务时间:" + p.UseTime +
" " + "需要时间:" + p.NeedTime +
" " + "优先级:" + p.Perior +
" " + "状态:" + p.Status);
if (sequnce.size() > 0) {
System.out.println("当前就绪进程:");
for (PCB p1 : sequnce) {
System.out.println("进程编号:" + p1.Id +
" " + "服务时间:" + p1.UseTime +
" " + "需要时间:" + p1.NeedTime +
" " + "优先级:" + p1.Perior +
" " + "状态:" + p1.Status);
System.out.println("--------------------------------------------------------------------------");
}
} else {
System.out.println("当前系统中已经没有就绪进程!");
}
System.out.println('\n');
}
}
第二步:创建一个Menu类
import java.util.Scanner;
class Menu//主界面菜单
{ Scanner sc=new Scanner(System.in);
int print() { System.out.println("********************************************");
System.out.println(" 进调度算法演示");
System.out.println("********************************************");
System.out.println(" 1.先来先服务(FCFS)算法");
System.out.println(" 2.时间片轮换(RR)算法");
System.out.println(" 3.退出该程序");
System.out.print("请选择所要采用的算法:");
int flag=sc.nextInt(); return flag; }
void select() {
int flag=print();
switch (flag)
{ case 1: Found Process1=new Found();Process1.FCFS(); print();
case 2: Found Process2=new Found(); Process2.RR(); print();
case 3: System.exit(0);
default: break; }
}
}
第三步:创建一个PCB类
import java.util.ArrayList;
import java.util.Scanner;
public class PCB {
int Id;//进程编号
int UseTime;//服务时间
int NeedTime;//需要时间
int Perior;//优先级
String Status;//状态
PCB() {
Id++;
UseTime = 0;
NeedTime = (int) Math.round(Math.random() * 6) + 1;//随机产生需要时间
Perior = (int) Math.round(Math.random() * 5) + 1;//随即产生优先级 Status="Ready";//初始状态为就绪 } }
}
}
第四步:创建一个ProcessControl 类
public class ProcessControl {
public static void main(String args[])
{
PCB pcb=new PCB();
Menu Tencent=new Menu();
Tencent.select();
}
}
4536





