Java实现模拟进程处理过程(多状态的时间片轮转)

实现步骤如下:

1.实现Process类(状态用Enum标识)

2.构造四个队列(运行队列,阻塞队列,就绪队列,完成队列)

3.初始化时将进程分类放入相应队列中

4.实现改变优先级方法,按优先级排序队列

5.模拟进程处理(策略为时间片不断轮转,发现运行队列中某进程所需时间小于时间片时,将就绪队列(已排序)中的一个进程放入运行队列中,阻塞队列中一个进程放入就绪队列中。下次时间片轮转的时候运行队列必定有一个进程进入完成队列,基本保持队列的稳定。当阻塞队列中的进程处理完时,进程模拟结束)

6.进行部分方法的单元测试

 

测试数据如下:

2

8

A 3 2  1  0 RUNNING
B 6 5  2  1 READY
C 1 8  5  2 WAITING
D 9 6  8  4 RUNNING
E 1 9  3  1 READY
F 7 7  6  2 WAITING
G 8 15 10 0 WAITING
H 7 5  11 0 READY

 

运行结果如下:

 

测试结果如下:

 

 

写一个进程类

package com.process.test;

public class Process {
    private int needTime;
    private int priority;
    private int arriveTime;
    private int usedTime;
    private String name;
    private State state;

    /**
     * Initial Process
     * @param name Process name
     * @param priority Process priority
     * @param needTime Process needTime
     * @param arriveTime Process arriveTime
     * @param usedTime Process usedTime
     * @param state Process state
     */
    public Process(String name, int priority, int needTime, int arriveTime, int usedTime, State state) {
        this.name = name;
        this.arriveTime = arriveTime;
        this.needTime = needTime;
        this.priority = priority;
        this.usedTime = usedTime;
        this.state = state;
    }

    public int getArriveTime() {
        return arriveTime;
    }

    public int getNeedTime() {
        return needTime;
    }

    public int getPriority() {
        return priority;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setNeedTime(int needTime) {
        this.needTime = needTime;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    public int getUsedTime() {
        return usedTime;
    }

    public void setUsedTime(int usedTime) {
        this.usedTime = usedTime;
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }
}

 

进程状态用Enum标识

package com.process.test;

public enum State {
    FINISHED, RUNNING, WAITING, READY;
}

 

模拟进程处理类

package com.process.test;

import com.process.test.Process;
import com.process.test.State;

import java.util.*;

public class SimulateDealProcess {
    static int pTime;
    static List<Process> readyQueue;
    static List<Process> waitingQueue;
    static List<Process> queue;
    static List<Process> finishedQueue;
    static final String READY = "READY", WAITING = "WAITING", FINISHED = "FINISHED", RUNNING = "RUNNING";

    static Comparator<Process> comparator = new Comparator<Process>() {
        @Override
        public int compare(Process o1, Process o2) {
            if (o1.getPriority() >= o2.getPriority()) {
                return -1;
            } else if (o1.getPriority() < o2.getPriority()) {
                return 1;
            } else {
                if (o1.getArriveTime() < o2.getArriveTime()) {
                    return -1;
                } else {
                    return 1;
                }
            }
        }
    };

    public static void main(String[] args) {
        queue = new LinkedList<>();
        readyQueue = new LinkedList<>();
        waitingQueue = new LinkedList<>();
        finishedQueue = new LinkedList<>();

        int count;
        int needTime;
        int priority;
        int arriveTime;
        int usedTime;
        String name;
        Process process;
        String processState;
        State state;

        Scanner sca = new Scanner(System.in);
        System.out.println("Please input time piece(Integer)");
        pTime = sca.nextInt();
        while (pTime <= 0) {
            System.out.println("Please input valid time piece!");
            pTime = sca.nextInt();
        }
        System.out.println("Please input number of processes");
        count = sca.nextInt();
        while (count <= 0) {
            System.out.println("Please input valid number of processes");
            count = sca.nextInt();
        }

        System.out.println("Please input process name, priority, needTime, arrivalTime, usedTime, state:");

        for (int i = 0; i < count; i++) {
            name = sca.next();
            priority = sca.nextInt();
            needTime = sca.nextInt();
            arriveTime = sca.nextInt();
            usedTime = sca.nextInt();
            processState = sca.next();

            state = State.valueOf(processState);
            process = new Process(name, priority, needTime, arriveTime, usedTime, state);
            switch (state) {
                case READY:readyQueue.add(process);break;
                case RUNNING:queue.add(process);break;
                case FINISHED:finishedQueue.add(process);break;
                case WAITING:waitingQueue.add(process);break;
                default:
                    System.out.println("Invalid state, state can only be :FINISHED, RUNNING, WAITING and READY;");
            }
        }

        sortQueue(queue);
        sortQueue(finishedQueue);
        sortQueue(readyQueue);
        sortQueue(waitingQueue);

        //choice flag
        int flag;
        //break while sFlag
        boolean sFlag = true;
        //choose queue
        String chooseQueue;
        // index of queue
        int index;
        int priotity;
        while (sFlag) {
            System.out.println("1.View ReadyQueue State    2.View RunningQueue State" +
                    "    3.View WaitingQueue State\t" +
                    "4.View FinishedQueue State\n5.Process processing Simulation" +
                    "    6.Change process priority    7.exit");
            flag = sca.nextInt();
            switch (flag) {
                case 1:print(readyQueue);break;
                case 2:print(queue);break;
                case 3:print(waitingQueue);break;
                case 4:print(finishedQueue);break;
                case 5:dealProcess();break;
                case 6:
                    System.out.println("Please input queue name(READY, WAITING, RUNNING, FINISHED), " +
                            "position, priority:");
                    chooseQueue = sca.next();index = sca.nextInt();priority = sca.nextInt();
                    changePriority(chooseQueue, index, priority);break;
                case 7:sFlag = false;break;
                default:
                    System.out.println("Command Invalid");
            }
        }
    }

    public static void sortQueue(List<Process> processList) {
        Collections.sort(processList, comparator);
    }

    public static boolean judgeRange(List<Process> queue, int index) {
        return (index <= queue.size()) && (index > 0);
    }

    public static void changePriority(String strQueue, int index, int priority) {
        Process process;
        List<Process> tempQueue = null;
        switch (strQueue) {
            case READY:tempQueue = readyQueue;break;
            case WAITING:tempQueue = waitingQueue;break;
            case RUNNING:tempQueue = queue;break;
            case FINISHED:tempQueue = finishedQueue;break;
            default:break;
        }

        if (tempQueue == null) {
            System.out.println("have no " + strQueue + " queue");
        } else if ((judgeRange(tempQueue, index))) {
            process = tempQueue.get(index-1);
            process.setPriority(priority);
        } else {
            System.out.println("Range Invalid");
        }

    }



    /*
A 3 2  1  0 RUNNING
B 6 5  2  1 READY
C 1 8  5  2 WAITING
D 9 6  8  4 RUNNING
E 1 9  3  1 READY
F 7 7  6  2 WAITING
G 8 15 10 0 WAITING
H 7 5  11 0 READY
             */

    public static void dealProcess() {
        Process process, waitingProcess, readyProcess;
        Iterator<Process> readyIterator, waitingIterator, iterator;
        boolean endFlag = true;

        while (endFlag) {
            iterator = queue.iterator();
            readyIterator = readyQueue.iterator();
            waitingIterator = waitingQueue.iterator();
            while (iterator.hasNext()) {
                process = iterator.next();
                try {
                    Thread.sleep(1000 * pTime);
                    if (process.getNeedTime() - pTime <= 0) {
                        process.setState(State.FINISHED);
                        process.setUsedTime(process.getUsedTime() + process.getNeedTime());
                        process.setNeedTime(0);
                        finishedQueue.add(process);
                        iterator.remove();

                        System.out.println("Process" + process.getName() + " have been finished!");
                        print(finishedQueue);
                    } else {
                        process.setUsedTime(process.getUsedTime() + pTime);
                        process.setNeedTime(process.getNeedTime() - pTime);
                        print(queue);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            if (readyIterator.hasNext()) {
                readyProcess = readyIterator.next();
                readyProcess.setState(State.RUNNING);
                queue.add(readyProcess);
                readyIterator.remove();
                System.out.println("Process " + readyProcess.getName() + " come in RunningQueue!");
                if (waitingIterator.hasNext()) {
                    waitingProcess = waitingIterator.next();
                    waitingProcess.setState(State.READY);
                    readyQueue.add(waitingProcess);
                    System.out.println("Process " + waitingProcess.getName() + " come in ReadyQueue!");
                    waitingIterator.remove();
                }
                sortQueue(queue);
            } else if (queue.isEmpty()) {
                endFlag = false;
            }

        }
    }

    public static void print(List<Process> queue) {
        System.out.println("Name \tPriority \t\tNeedTime \t\tArrivalTime \t\tUsedTime \t\tProcessState");
        for (Process p : queue) {
            System.out.printf("%-5s %3d     \t\t\t%02ds     \t\t%02ds     " +
                            "\t\t\t%02ds      \t\t%s\n\n", p.getName(), p.getPriority(), p.getNeedTime(),
                    p.getArriveTime(), p.getUsedTime(), p.getState());
        }
    }


    //Test print method
    public static String processInformation(List<Process> queue, int index) {
        Process process = queue.get(index);
        return process.getName() + " " + process.getPriority() + " " +
                process.getNeedTime() + " " + process.getArriveTime() + " " + process.getUsedTime()
                + " " + process.getState();
    }

}

 

单元测试类

package test;

import javafx.concurrent.Worker;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before; 
import org.junit.After;
import com.process.test.Process;
import com.process.test.State;
import com.process.test.SimulateDealProcess;
import java.util.LinkedList;
import java.util.List;

/**
* com.process.test.SimulateDealProcess Tester.
* 
* @author <Authors name>
* @version 1.0 
*/ 
public class SimulateDealProcessTest {
    LinkedList<Process> processes;


@Before
public void before() throws Exception {
    processes = new LinkedList<Process>();
}

/** 
* 
* Method: sortQueue(List<com.process.test.Process> processList)
* 
*/ 
@Test
public void testSortQueue() throws Exception { 
//TODO: Test goes here...
    processes.add(new Process("A", 4,3, 3, 0, State.RUNNING));
    processes.add(new Process("B", 4, 6, 1, 1, State.RUNNING));
    processes.add(new Process("C", 7, 10, 4, 2, State.RUNNING));
    SimulateDealProcess.sortQueue(processes);
    Assert.assertEquals("C", processes.get(0).getName());
    Assert.assertEquals("B", processes.get(1).getName());
    Assert.assertEquals("A", processes.get(2).getName());
}

/** 
* 
* Method: judgeRange(List<com.process.test.Process> queue, int index)
* 
*/ 
@Test
public void testJudgeRange() throws Exception { 
//TODO: Test goes here...
    processes.add(new Process("A", 4,3, 3, 0, State.RUNNING));
    processes.add(new Process("B", 4, 6, 1, 1, State.RUNNING));
    processes.add(new Process("C", 7, 10, 4, 2, State.RUNNING));
    processes.add(new Process("E", 9, 5, 4, 2, State.RUNNING));
    Assert.assertFalse(SimulateDealProcess.judgeRange(processes, 5));
    Assert.assertFalse(SimulateDealProcess.judgeRange(processes, -2));
    Assert.assertFalse(SimulateDealProcess.judgeRange(processes, 0));
    Assert.assertTrue(SimulateDealProcess.judgeRange(processes, processes.size() - 1));
    Assert.assertTrue(SimulateDealProcess.judgeRange(processes, processes.size()));
}

/**
*
* Method: print(List<com.process.test.Process> queue)
*
*/
@Test
public void testPrint() throws Exception {
//TODO: Test goes here...
    processes.add(new Process("B", 6,5, 2, 1, State.READY));

    Assert.assertEquals("B 6 5 2 1 READY", SimulateDealProcess.processInformation(processes, 0));

}
} 

 

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
流程图,代码,截图三、程序源代码: #include"stdlib.h" #include"stdio.h" #include"string.h" /********** globle structure and viable ******/ struct PCB { int P_Id; //PCB的ID号 char P_Name[10]; //PCB的名称 char P_State[10]; //PCB状态 int P_Runtime; //PCB的所需要的运行时间 int P_Requiry; //PCB所需要的资源要求 struct PCB * next ; //PCB块的下一个指针 } ; struct PCB * Create_state; //创建状态 struct PCB * Run_state; //运行状态 struct PCB * Ready_state; //就绪状态 struct PCB * Block_state; //阻塞状态 struct PCB * Exit_state; //退出状态 int signal4=0; //标示进程4的完成状态 int signal5=0; //标示进程5的完成状态 void InsertQueue(struct PCB **head,struct PCB *node) /* insert node function */ { struct PCB * p,*q; node->next=NULL; if(*head==NULL) //如果队列为空 { *head=node; } Else //队列不空 { p=*head; q=p->next; while(q!=NULL) //找到最后的元素位置 { p=q; q=q->next; } p->next=node; //将节点插入队列 } } void DeleteQueue(struct PCB **head,struct PCB *node) //撤销进程,从队列中删除元素 { struct PCB *p,*q; q=*head; if(*head==NULL||node==NULL) //如果队列为空,返回 return ; if(*head==node) //如果要删除的元素是队首元素 { *head=(*head)->next; return; } Else //如果不是队列的首元素 { while(q->next!=p&&q->next!=NULL) q=q->next; q=p->next; p->next=NULL; } } void Display_Process(struct PCB * node) //打印进程状态的元素函数 { printf("\n\nthis process Id is : %d \n",node->P_Id); printf("this process name is : %s \n",node->P_Name); printf("this process state is : on %s \n ",node->P_State); printf("this process Runtime is : %d \n",node->P_Runtime); if(node->P_Requiry) printf("this process resource is ready \n"); else printf("this process resource is not ready ! \n"); } void DispatchToBlock(struct PCB *node) // /* dispatch to block function*/ { //调度到阻塞状态的函数 //struct PCB *p=(struct PCB *)malloc(sizeof(struct PCB)); if(!node->P_Requiry) //如果所需要的资源没有满足则,调度到阻塞状态 { strcpy(node->P_State,"block"); InsertQueue(&Block_state,node); //插入到阻塞队列 Display_Process(node); } } void DispatchToReady(struct PCB *node) // dispatch to ready state { //调度到就绪状态的函数 if(node->P_Requiry) //如果所需的资源满足,则调度 { strcpy(node->P_State,"Ready"); InsertQueue(&Ready_state,node); Display_Process(node); } } void DispatchBlockToReady() //dispatch the process to readyqueue { //从阻塞状态调度到就绪状态函数 struct PCB*p,*q; q=Block_state; while(q!=NULL) //如果阻塞状态队列不空 { p=q; q=q->next; if(signal4&&p->P_Id==4) //如果所需要的资源满足 { DeleteQueue(&Block_state,p); strcpy(p->P_State,"ready"); InsertQueue(&Ready_state,p); printf("process4 will be in the state of ready!\n"); Display_Process(p); } if(signal5&&p->P_Id==5) { DeleteQueue(&Block_state,p); strcpy(p->P_State,"ready"); InsertQueue(&Ready_state,p); printf("process5 will be in the state of ready!\n"); Display_Process(p); } } } void Create_Process() //创建进程函数 { int i; struct PCB *p; char name[10]; strcpy(name,"process"); for(i=1;iP_Id=i; name[7]=i+'0'; name[8]='\0'; strcpy(p->P_Name,name); strcpy(p->P_State,"create"); p->P_Runtime=1; //所需要的时间片为1 p->P_Requiry=0; Display_Process(p); sleep(4); printf(" \n process%d will be in the state of Block, waiting the resource ready \n\n",i); DispatchToBlock(p); //同时调度到阻塞队列 } for(i=3;iP_Id=i; name[7]=i+'0'; name[8]='\0'; strcpy(p->P_Name,name); strcpy(p->P_State,"create"); p->P_Requiry=1; if(i==6) //在这里个进程6所需要的时间片为2 p->P_Runtime=2; else p->P_Runtime=1; Display_Process(p); sleep(4); printf(" \n process%d will be in the state of Ready, waiting to run \n\n",i); DispatchToReady(p); } } void display(struct PCB **head) //打印各个状态队列里进程数目 { struct PCB *p,*q; p=*head; while(p!=NULL) { sleep(2); //printf("\n\n///////////////////////////////////\n"); printf("\n\nthis process Id is : %d \n",p->P_Id); printf("this process name is : %s \n",p->P_Name); printf("this process state is : on %s \n ",p->P_State); printf("this process Runtime is : %d \n",p->P_Runtime); if(p->P_Requiry) printf("this process resource is ready \n"); else printf("this process resource is not ready ! \n"); p=p->next; } } void Process_Run() //进程运行函数 { struct PCB *p,*q; p=Ready_state; q=p; while(p!=NULL) //就绪队列不空则继续执行 { if(p->P_RuntimeP_State,"running"); Display_Process(p); p->P_Runtime=p->P_Runtime-1; sleep(4); if(p->P_Runtime>0) //没有完成,则进入就绪队列 { printf("this process is not finished,will be dispatch to the ready queue!!\n"); DeleteQueue(&Ready_state,p); strcpy(p->P_State,"ready"); InsertQueue(&Ready_state,p); Display_Process(p); } Else //执行完成,则跳出,并发送相应的信息 { printf("\n\nProcess%d is finished and will be in the state of exit!\n\n",p->P_Id); if(p->P_Id==4) signal4=1; if(p->P_Id==5) signal5=1; } if(signal4||signal5) DispatchBlockToReady(); //如果资源满足,则将进程调度到就绪队列 q=q->next; p=q; } if(q==NULL) printf("\nthere is no process ready!\n STOP Machine!!!\n"); } int main(int argc,char * argv[]) //主函数 { int i; char c='c'; //界面 printf("\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \n"); printf("...................................Ding Hai bo\n"); printf("......Press s to start the process.......\n"); scanf("%c",&c); while(1) { if(c=='s')break; scanf("%c",&c); } Create_Process(); //调用创建进程函数 printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); printf("\n>>>>>>> Display the Ready queue >>>>>>>>>>>>>>>\n"); sleep(5); display(&Ready_state); ////////////////显示就绪队列里的进程 printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n"); printf("\n>>>>>>>> Display the Block queue >>>>>>>>>>>>\n"); sleep(5); //显示阻塞队列函数 display(&Block_state); ///////////////////// printf("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n"); printf("\n>>>>>>>> Now the process start to run >>>>>>>>>>>\n"); sleep(5); Process_Run(); //调用进程运行函数 } 都有
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值