操作系统实验-CPU进程调度和内存分配 java版

时间:2024.4.13

操作系统实验

第一期     项目开发实现

实验名称         EXP.1 CPU Scheduling

Exp.2 Allocation & Reclaim

实验内容        

    一,选择一个调度算法,实现处理机调度;

二,处理机调度过程中,主存储器空间的分配和回收;

实验目的

一,多道系统中,当就绪进程数大于处理机数时,须按照某种策略决定哪些进程优先占用处理机。本实验模拟实现处理机调度,以加深了解处理机调度的工作;

二,帮助了解在不同的存储管理方式下,应怎样实现主存空间的分配和回收;

实验题目

一,(1)设计一个按照优先权调度算法实现处理机调度的程序;

    (2)设计按时间片轮转实现处理机调度的程序;

二,在可变分区管理方式下,采用最先适应算法实现主存空间的分配和回收;

实验要求

一,(a),PCB内容: 进程名/PID; 要求运行时间(单位时间); 优先权; 状态; PCB指针;   ——(因课程内容原因,这个指针在设计中没用)

         1,可随机输入若干进程,并按优先权排序;

         2,从就绪队列首选进程运行:优先权-1/ 要求运行时间-1;要求运行时间=0时,撤销该进程;

         3,重新排序,进行下一轮调度;

    (b),最好采用图形界面;

    (c),可随时增加进程;

    (d),规定道数,设置后备队列和挂起状态。若内存中进程数少于规定道数,可自动从后备队列调度一作业进入。被挂起进程如=入挂起队列,设置解挂功能用于将指定挂起进程解挂入就绪队列;

     (e),每次调度后,显示各进程状态;

二,(a),自行假设主存空间大小,预设操作系统所占大小并构造未分分区表;

    表目内容:起址、长度、状态(未分/空表目)

   (b),结合实验一,PCB增加为:{PID,要求运行时间,优先权,状态,所需内存大小,主存起始位置,PCB指针(失效)};

   (C)采用最先适应算法分配主存空间;

   (D),进程完成后,回收主存,并与相邻空闲分区合并;

实验过程及分析

1,         初步设计:

2,         详细设计:

    (a),操作系统知识回顾:

(1)作业进入内存中,由CPU分配产生PCB属性,并通过PCB记录进程状态,实验即以PCB代表进程模拟调度过程;

(2)在多道系统中,多道系统中,当就绪进程数大于处理机数时,须按照某种策略决定哪些进程优先占用处理机,本实验采用优先级;

(3),进程调度时,规定若就绪队列进程数少于6个,则自动从后备队列调入一个作业;

(4),系统会将占有较多资源、预期结果不符合要求的进程自动挂起,并回收所占资源,而本实验设置为手动挂起;

(5),在适宜条件下,系统会将挂起的进程自动解挂,而且只解挂到就绪队列;本实验为简化操作,设置为手动解挂,若解挂条件合适(即CPU各种资源可用),则解挂到就绪队列,并分配内存;若解挂条件不适宜,则解挂至后备队列,但不分配内存(实际上这是不对的,因为作业进入内存,由CPU标记PCB后,不能撤销PCB再返回内存,除非该进程执行结束,但本程序为体现解挂的意思,还是错误地设计为可以解挂到后备队列,读者需注意,这个功能可以在代码中注销,另外也希望有高手可以改进);

(b),实验程序设计:

     (1),本实验采用java语言编程,并实现GUI界面显示;

     (2),为体现java语言面对对象程序设计的特点,实验设计为ProcessPCB、MemoryItem类封装PCB和所分配的内存各自的属性与方法;用ProcessRecords、MemoryRecords类封装数组方法;用SingleCPUScheduling实现GUI界面显示;

      (3),ProcessPCB类中,定义PCB的进程名、要求运行时间、优先级、状态、主存起始位置、所需内存大小这6个属性,并定义各属性的get和set方法,定义equals方法用于对比类的属性,定义toString方法得到类属性的字符串,定义run方法封装优先权-1/ 要求运行时间-1的过程;MemoryItem类中,定义可分分区表每一可分记录的主存起始位置、内存大小及其get和set方法,定义toString方法得到可在界面显示的字符串;

      (4),ProcessRecords封装PCB数组的添加元素addItem和删除元素removeItem方法,并构造函数getItem通过参数ProcessPCB和String查找数组元素,定义getNumberOfItems取数组大小,定义getItemsPriorities方法取所有数组元素的toString方法用于界面显示,定义iterator方法取得数组的迭代器;

      (5),MemoryRecords用同样的设计思想封装以MemoryItem为数组元素的各属性和方法;

      (6)SingleCPUScheduling类继承JFrame类,实现界面化显示;与上面相对应,实例化ProcessRecords(3次)和MemoryRecords(1次)作为私有变量,分别作为后备队列、就绪队列、挂起队列和内存可分分区表;在界面设计中,设计后备队列、挂起队列(附带解挂umount按钮)、就绪队列(附带挂起suspend按钮)可分分区表列表显示框,设置PCB添加框,附带添加至后备队列(addToBackup)、添加至就绪队列(addToReady)按钮,以及CPU当前执行状态显示框、系统日志显示框,和开始调度(systemStart)按钮,优先级和时间片单选按钮,以及时间片显示标签和文本编辑框;

      (7)界面设计详解;后备队列显示框用于显示已添加至后备队列的ProcessRecords属性信息,其中主存起始位置默认为-1,表示未分配;挂起队列显示框用于显示从就绪队列挂起的PCB,其中属性“主存起始位置”(MemoryBase)将由非负数变为-1,表示挂起后收回内存;就绪队列显示框中显示就绪队列属性,其中“主存起始位置”均为非负,表示一分配内存;PCB信息添加框分列PCB6个属性显示标签和可编辑文本框,和添加按钮,用于添加PCB;系统日志显示框附属时间片显示标签和可编辑文本编辑框,可由用户决定时间片大小;

           对于实验一,界面如下:

      

[FHLC1] 

以上由SingleCPUScheduling001.java(另需ProcessPCB.java和PCBRdecords.java)

(8)附属功能添加完善;最重要的是为程序添加线程,是程序能以停顿一段时间的频率自动[FHLC2] 运行;后备队列、挂起队列添加total显示标签和不可编辑文本显示框,用于显示各自数组中元素数目,挂起队列附属删除(remove)按钮,可删除挂起队列中的元素;后备、挂起、就绪队列均添加监听器,用于响应用户单击操作,可以在PCB信息添加框显示用户单击的那一条PCB的信息;PCB信息添加框附属reset按钮,用于一键清空信息框中信息,方便输入;系统日志面板附属系统暂停(systemPause)和系统重置(systemReset)按钮,分别用于暂停运行(方便用户观察当前运行结果)和重置系统(方便用户重复使用程序,免去关闭后重启本程序的麻烦);最终界面如图:

实验结果报告级分析

1,            程序完成了实验所有的基本要求;

2,            本程序还存在一些技术上的问题,使得程序不能尽善尽美;如,PCB信息添加框没有“随机置入就绪队列”功能,添加PCB信息仍显得繁琐;就绪队列的挂起功能在程序自动运行时,存在反应异常(反应延迟或直接无反映);可分分区表只显示了当前可分的内存,没有显示已分的PCB及其对应内存使用情况,且没有利用图形和丰富的颜色来更好的展示;时间片设计还需要改进,使用效率不高;系统重置功能存在响应延迟的问题;另外,界面不够美观;还需要不断改进;

实验感想

通过这次实验,我对操作系统的进程调度和内存分配管理有了更加深入的了解,对操作系统内部的工作原理有了进一步的认识;

通过编程,也巩固了我的程序设计和代码编写的能力,实验过程中遇到的各种问题以及解决问题的过程与方法,都是我获益匪浅;

同时,程序的不完善,也将促使我在课程之后,继续学习、理解课程内容,并尽一切努力不断完善程序,做到尽善尽美;

程序代码

完整版(初学java,菜鸟级别,当然是将所学的全部照办照抄,实为臃肿,可为初学者引以为戒,注意代码质量!)

这里谨贴出十分臃肿的代码,仅供初学者交流经验,重在开发的思想,了解开发的流程,而01版(精简版)代码在后面;

ProcessPCB.java

package src;

public class ProcessPCB {

//  backupBAK 后备  ready 就绪  suspend 挂起 memory内存

    private String PID;

    private int RequiredTime;

//  private String Priority;

    private int Priority;

    private String Status;

    private int MwmoryBase = 0000;

    private int MemoryLimit;

//  private String PCBPointer;

    public ProcessPCB(String initpID, int initRTime, int initpriority,

                      String status, int initBase, int initLimit) {

      

       this.PID = initpID;

       this.RequiredTime = initRTime;

       this.Priority = initpriority;

       this.Status = status;

       this.MwmoryBase = initBase;

       this.MemoryLimit = initLimit;

    }

   

    public String getPID() {

       if(this.PID == null)

           return " ";

       else

           return this.PID;

    }

   

    public void setPID(String pid[FHLC3] ) {

       if(pid == null)

           this.PID = " ";

       else

           this.PID = pid;

    }

   

    public int getRequiredTime() {

       return this.RequiredTime;

    }

   

    public void setRequiredTime(int time) {

       this.RequiredTime = time;

    }

   

    public int getPriority() {

       return this.Priority;

    }

   

    public void setPriority(int priority) {

       this.Priority = priority;

    }

   

    public String getStatus() {

       if(this.Status == null)

           return " ";

       else

           return this.Status;

    }

   

    public void setStatues(String statues) {

       if(statues == null)

           this.Status = " ";

       else

           this.Status = statues;

    }

   

    public int getMemoryBase() {

       return this.MwmoryBase;

    }

   

    public void setMemoryBase(int base) {

       this.MwmoryBase = base;

    }

   

    public int getMemoryLimit() {

       return this.MemoryLimit;

    }

   

    public void setMemoryLimit(int limit) {

       this.MemoryLimit = limit;

    }

   

    public boolean equals(ProcessPCB  pcb) {

      

       if(pcb.getPID() == this.getPID())  {

           return true;

       }

       else return false;

    }

   

    public String toString() {

       return this.getPID() + "_" + this.getRequiredTime() + "_" + this.getPriority() + "_"

                + this.getStatus() + "_" + this.getMemoryBase() + "_" + this.getMemoryLimit() + "\n";

    }

   

    public void run() {

       this.RequiredTime = this.RequiredTime-1;

       this.Priority = this.Priority-1;

    }

   

}

MemoryItem.java

package src;

public class MemoryItem {

    private int memoryBase=0;

    private int memoryLimit=0;

    private int availableStatus=0;

   

    public MemoryItem(int initMemoryBase, int initMemoryLimit) {

       this.memoryBase = initMemoryBase;

       this.memoryLimit = initMemoryLimit;

    }

   

    public int getMemoryBase() {

       return this.memoryBase;

    }

    public void setMemoryBase(int base) {

        this.memoryBase = base;

    }

   

    public int getMemoryLimit() {

       return this.memoryLimit;

    }

    public void setMemoryLimit(int limit) {

        this.memoryLimit = limit;

    }

    public int getStatus() {

       return this.availableStatus;

    }

    public void setStatus(int status) {

        this.memoryBase = status;

    }

   

    public String toString() {

        return this.getMemoryBase() + "_" + this.getMemoryLimit() + "\n";

    }

   

}

PCBRecords.java

package src;

import java.util.ArrayList;

import java.util.Iterator;

public class PCBRecords implements Iterable<ProcessPCB> {

      

       private ArrayList<ProcessPCB> PCBItems;

      

    public ArrayList<ProcessPCB> getPCBItems() {    

              return this.PCBItems;

       }

   

    public PCBRecords() {

              this.PCBItems = new ArrayList<ProcessPCB>();

       }

   

    public void addItem(ProcessPCB PcbItem) {

              this.PCBItems.add(PcbItem);

       }

   

    public void removeItem(ProcessPCB PCbItem) {   

             this.PCBItems.remove(PCbItem);

      }

   

    public ProcessPCB getItem(ProcessPCB processPCB) { 

             for (ProcessPCB pCbItem : this.PCBItems) {

                              if (pCbItem.equals(processPCB)) {                               

                                      return pCbItem;

                                  }

                            }                          

                     return null;

      }

     

    public ProcessPCB getItem(String pid) { 

             for (ProcessPCB pcBItem : this.PCBItems) {

                              if (pcBItem.getPID().equals(pid)) {                                      

                                      return pcBItem;

                                  }

                            }                          

                     return null;

      }

   

    public int getNumberOfItems() {      

             return this.PCBItems.size();

      }

    public String[] getItemsProperties() {      

             String itemsProperties[] = new String[getNumberOfItems()];

            

             int i = 0;

        for(Iterator iterator1 = PCBItems.iterator(); iterator1.hasNext();)

        {

               ProcessPCB stu_Item = (ProcessPCB)iterator1.next();

               itemsProperties[i++] = stu_Item.toString();

        }

        return itemsProperties;

      }

       public Iterator<ProcessPCB> iterator() {

              return this.PCBItems.iterator();

       }

}

MemoryRecords.java

package src;

import java.util.ArrayList;

import java.util.Iterator;

public class MemoryRecords implements Iterable<MemoryItem> {

       private ArrayList<MemoryItem> memoryItems;

       public Iterator<MemoryItem> iterator() {

              // TODO Auto-generated method stub

              return this.memoryItems.iterator();

       }

    public ArrayList<MemoryItem> getMemoryItems() {

             

              return this.memoryItems;

       }

   

    public MemoryRecords() {

           this.memoryItems = new ArrayList<MemoryItem>();

    }

   

    public void addItem(MemoryItem newMemoryItem) {

           this.memoryItems.add(newMemoryItem);

    }

    public void removeItem(MemoryItem momoryItem) {

           this.memoryItems.remove(momoryItem);

    }

   

    public MemoryItem getMomoryItem(MemoryItem item) {

           for(MemoryItem mItem : this.memoryItems) {

                  if(mItem.equals(item)) {

                         return mItem;

                  }

           }

           return null;

    }

    public MemoryItem getMemoryItem(int base) {

           for(MemoryItem mItem : this.memoryItems) {

                  if(mItem.getMemoryBase() == base) {

                         return mItem;

                  }

           }

           return null;

    }

   

    public int getNumberOfItems() {             

             return this.memoryItems.size();

      }

   

    public String[] getItemsProperties() {

           String itemsProperties[] = new String[getNumberOfItems()];

           int i=0;

           for(Iterator iterator1 = this.memoryItems.iterator(); iterator1.hasNext(); ) {

                  MemoryItem mmItem = (MemoryItem) iterator1.next();

                  itemsProperties[i++] = mmItem.toString();//????

           }

           //System.out.println(itemsProperties + "\n");

           if(itemsProperties == null) {

                  itemsProperties[0] = "      ";

           }

           return itemsProperties;

    }

}

SingleCPUSchedulingGUI001.Java

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

import src.SingleCPUSchedulingGUI001.AddToBAKListener;

import src.SingleCPUSchedulingGUI001.AddToReadyListener;

import src.SingleCPUSchedulingGUI001.RemoveListener;

import src.SingleCPUSchedulingGUI001.ResetListener;

import src.SingleCPUSchedulingGUI001.ResetSystemListener;

import src.SingleCPUSchedulingGUI001.StartSystemListener;

import src.SingleCPUSchedulingGUI001.SuspendListener;

import src.SingleCPUSchedulingGUI001.SystemPauseListener;

import src.SingleCPUSchedulingGUI001.UmountListener;

import src.SingleCPUSchedulingGUI001.priotiryListener;

import src.SingleCPUSchedulingGUI001.timeslicListener;

import java.io.*;

import java.text.*;

public class SingleCPUSchedulingGUI001 extends JFrame {

      

       private int systemStatues;  //注意static 属性

          /*define  0--system prepare status--system reset and re-prepare  1--system start  2--system pause 3--system stop*/

       /* Standar error stream */

       static private PrintWriter  stdErr = new  PrintWriter(System.err, true);

      

       static private int WIDTH = 600, HEIGHT = 700;            // the size of the Frame 主面板                                             

       /* 各列表对应的面板规格*/

/*    对应各名词释义  backupBAK 后备  ready 就绪  suspend 挂起  memory内存  */

       static private int BackupBAK_CELL_SIZE = 250, BackupBAK_LIST_ROWS = 10;       //后备队列

       static private int Suspend_CELL_SIZE = 250, Suspend_LIST_ROWS = 10;         //挂起队列

       static private int Ready_CELL_SIZE = 200, Ready_LIST_ROWS = 6;              //就绪队列

       static private int CPU_ROWS = 10, CPU_COLS = 22;                         //CPU面板

       static private int STATUS_ROWS = 8, STATUS_COLS = 30;                   //系统状态面板

    private int timeslice = 1;                              //设置时间片大小

    private int systemStatus=0;        //设置系统状态 0——系统预备状态,等待开始,1——系统运行状态,2——系统暂停状态

       static private int TOTAL__TEXTFIELD_SIZE = 10;         // Size total text field 记录各队列元素个数

      

       private JList backupList, suspendList, readyList;  //各队列相对应的数组列表

     //   进程添加框中的"添加至后备队列","添加至就绪队列","重置"Button

       private JButton addToBAKButton, addToReadyButton, resetButton;

          //就绪队列框中的"挂起",挂起队列框中的"解挂","删除"Button

       private JButton suspendButton, umountButton, removeButton;

              //Status面板中的"启动系统","重置系统"Button

       private JButton startButton, pauseButton, resetSyatemButton;  

                   //优先级和时间片单选钮及时间片显示框

       private JRadioButton priorityJRB, timesliceJRB;

       private JLabel timesliceSizeLabel;   

       private JTextField timesliceJtf;

            //后备面板、进程添加面板、挂起面板、内存面板

       private JPanel backupBAKPanel, PCBItemPanel, suspendedPanel;

                      //后备队列、挂起队列元素总数标签

       private JLabel backupTotalLabel, suspendTotalLabel;

    //进程信息标签  进程编号PID,所需运行时间requiredTime,优先级priority,当前状态statues,内存中的基址base,所需内存大小limit

       private JLabel PIDLabel, requiredTimeLabel, priorityLabel, statuesLabel;

            //后备队列、挂起队列元素总数文本框(不可编辑)

       private JTextField backupTotalTextField, suspendTotalTextField;

       //进程信息文本框 PID(可编辑),requiredTime(可编辑),priority(可编辑),status(不可编辑),base(不可编辑),limit(可编辑)

       private JTextField PIDTextField, requiredTimeTextField, priorityTextField, statusTextField;

            //CPU状态显示文本域(不可编辑),status信息文本域(用于现实程序每一步的操作和影响,不可编辑)

       private JTextArea CPUTextArea, statuesTextArea;

       //后备队列PCB数组,就绪、挂起,——内存(可分分区表)

       PCBRecords backupPCB, readyPCB, suspendedPCB;

      

       public static void main(String[] args) throws IOException {

              // TODO Auto-generated method stub

              new SingleCPUSchedulingGUI001().initFrame();

       }

      

       public void initFrame() {

                    

              backupList = new JList();

              backupList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

              backupList.setVisibleRowCount(BackupBAK_LIST_ROWS);

              backupList.setFixedCellWidth(BackupBAK_CELL_SIZE);        

              suspendList = new JList();

              suspendList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

              suspendList.setVisibleRowCount(Suspend_LIST_ROWS);

              suspendList.setFixedCellWidth(Suspend_CELL_SIZE);             

              readyList = new JList();

              readyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

              readyList.setVisibleRowCount(Ready_LIST_ROWS);

              readyList.setFixedCellWidth(Ready_CELL_SIZE);      

             

              suspendButton = new JButton("Suspend");

              addToBAKButton = new JButton("AddToBAK");

              addToReadyButton = new JButton("AddToReady");

              resetButton = new JButton("Reset");

              umountButton = new JButton("Umount");

              removeButton = new JButton("Remove");

              startButton = new JButton("StartSchuliding");

              pauseButton = new JButton("Pause");

              resetSyatemButton = new JButton("ResetSystem");

              priorityJRB = new JRadioButton("Priority", true);

              timesliceJRB = new JRadioButton("Timeslice");

      

              backupTotalLabel = new JLabel("Total:");

              backupTotalTextField = new JTextField("0", TOTAL__TEXTFIELD_SIZE);

              backupTotalTextField.setEditable(false);

              suspendTotalLabel = new JLabel("Total:");

              suspendTotalTextField = new JTextField("0", TOTAL__TEXTFIELD_SIZE);

              suspendTotalTextField.setEditable(false);

              timesliceSizeLabel = new JLabel("Timeslice");

              timesliceJtf = new JTextField("3", 5);

              timesliceJtf.setEditable(true);

             

              CPUTextArea = new JTextArea(CPU_ROWS, CPU_COLS);

              CPUTextArea.setEditable(false);

              statuesTextArea = new JTextArea(STATUS_ROWS, STATUS_COLS);

              statuesTextArea.setEditable(false);

             

/* north panel*/

       //     JPanel northPanel = new JPanel(new BorderLayout());

              JPanel northPanel = new JPanel(new GridLayout(1, 3));

//            JPanel north = new JPanel(new BorderLayout());

             

              // ProcessPCB item information Panel

              PCBItemPanel = new JPanel(new BorderLayout());

              PCBItemPanel.setBorder(

                            BorderFactory.createTitledBorder("PCBItem Information"));

             

              JPanel PCBItemButtonJPanel = new JPanel(new GridLayout(3, 1));

              PCBItemButtonJPanel.add(addToBAKButton);

              PCBItemButtonJPanel.add(addToReadyButton);

              PCBItemButtonJPanel.add(resetButton);

             

              PCBItemPanel.add(this.initPCBItemPanel(), BorderLayout.CENTER);

              PCBItemPanel.add(PCBItemButtonJPanel, BorderLayout.SOUTH);

             

           //backupBAKList Panel

              backupBAKPanel = new JPanel(new BorderLayout());

              backupBAKPanel.setBorder(BorderFactory.createTitledBorder("BackupList"));

             

        JPanel backupTotalPAnel = new JPanel();

        backupTotalPAnel.add(backupTotalLabel);

        backupTotalPAnel.add(backupTotalTextField);

        backupBAKPanel.add (

                            new JScrollPane(backupList,

                                          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                                          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);

        backupBAKPanel.add(backupTotalPAnel, BorderLayout.SOUTH);

       

//        north.add(backupBAKPanel, BorderLayout.WEST);

//        north.add(PCBItemPanel, BorderLayout.CENTER);

       

           // SuspendList Panel     

        suspendedPanel = new JPanel(new BorderLayout());

        suspendedPanel.setBorder(BorderFactory.createTitledBorder("SuspendList"));

       

        JPanel suspendedTotalPAnel = new JPanel();

        suspendedTotalPAnel.add(suspendTotalLabel);

        suspendedTotalPAnel.add(suspendTotalTextField);

                                              

        JPanel suspendComponentPanel = new JPanel(new GridLayout(1, 2));

        suspendComponentPanel.add(umountButton);

        suspendComponentPanel.add(removeButton);

       

        suspendedPanel.add (suspendedTotalPAnel, BorderLayout.NORTH);

        suspendedPanel.add (

                            new JScrollPane(suspendList,

                                          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                                          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);

        suspendedPanel.add(suspendComponentPanel, BorderLayout.SOUTH);

     

//        northPanel.add(north, BorderLayout.CENTER);

//        northPanel.add(suspendedPanel, BorderLayout.EAST);

        northPanel.add(backupBAKPanel);

        northPanel.add(PCBItemPanel);

        northPanel.add(suspendedPanel);

             

/* center Panel*/ 

        JPanel centrelPanel = new JPanel(new BorderLayout());

//        JPanel centrelPanel = new JPanel(new GridLayout(1, 3));

           

            // readyList panel

        JPanel readyListPanel = new JPanel(new BorderLayout());

        readyListPanel.setBorder(BorderFactory.createTitledBorder("ReadyList"));

        readyListPanel.add (

                         new JScrollPane(readyList,

                                       JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                                       JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));//, BorderLayout.CENTER

        readyListPanel.add (suspendButton, BorderLayout.SOUTH);

            // CPU panel

        JPanel CPUPanel = new JPanel();

        CPUPanel.setBorder(BorderFactory.createTitledBorder("CPU"));

        CPUPanel.add (new JScrollPane(CPUTextArea,

                         JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                         JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));

       

        centrelPanel.add(readyListPanel, BorderLayout.WEST);

        centrelPanel.add(CPUPanel, BorderLayout.CENTER);

/*statues panel*/

        JPanel southPanel = new JPanel(new BorderLayout());

       

        JPanel statuesPanel = new JPanel();

        statuesPanel.setBorder(BorderFactory.createTitledBorder("Statues"));

        statuesPanel.add (new JScrollPane(statuesTextArea,

                         JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                         JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); //, BorderLayout.CENTER

        //statuesPanel.setSize(400, 100);

        //statuesPanel.setPreferredSize(new Dimension(400, 10));

       

        JPanel systemContralButtonPanel = new JPanel(new GridLayout(6, 1));

        systemContralButtonPanel.setBorder(BorderFactory.createTitledBorder("systemContral"));

        ButtonGroup group = new ButtonGroup();

        group.add(priorityJRB);

        group.add(timesliceJRB);

        JPanel porityPanel = new JPanel(new GridLayout(1, 2));

        porityPanel.add(timesliceSizeLabel);

        porityPanel.add(timesliceJtf);

        systemContralButtonPanel.add(priorityJRB);

        systemContralButtonPanel.add(timesliceJRB);

        systemContralButtonPanel.add(porityPanel);

        systemContralButtonPanel.add(startButton);

        systemContralButtonPanel.add(pauseButton);

        systemContralButtonPanel.add(resetSyatemButton);

       

        southPanel.add(statuesPanel, BorderLayout.CENTER);

        southPanel.add(systemContralButtonPanel, BorderLayout.EAST);

     

//            arrange panels in window

              setLayout(new BorderLayout());

              add(northPanel, BorderLayout.NORTH);

              add(centrelPanel, BorderLayout.CENTER);         

              add(southPanel, BorderLayout.SOUTH);  //statuesPanel

             

//            start listening for list and buttons events             

              addToBAKButton.addActionListener(new AddToBAKListener());

              addToReadyButton.addActionListener(new AddToReadyListener());

              resetButton.addActionListener(new ResetListener());

              suspendButton.addActionListener(new SuspendListener());

              umountButton.addActionListener(new UmountListener());

              removeButton.addActionListener(new RemoveListener());

              startButton.addActionListener(new StartSystemListener());

              pauseButton.addActionListener(new SystemPauseListener());

              resetSyatemButton.addActionListener(new ResetSystemListener()); 

              priorityJRB.addActionListener(new priotiryListener());

              timesliceJRB.addActionListener(new timeslicListener());

              backupPCB = new PCBRecords();

              readyPCB = new PCBRecords();

              suspendedPCB = new PCBRecords();

             

              backupList.setListData(backupPCB.getItemsProperties());

              readyList.setListData(readyPCB.getItemsProperties());

              suspendList.setListData(suspendedPCB.getItemsProperties());

             

              this.setTitle("CPUSchudling");

              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

              this.setSize(WIDTH, HEIGHT);

              this.setResizable(true);

              this.setVisible(true);

              this.setLocation(200, 10);

       }

      

       public JPanel initPCBItemPanel() {

             

              JPanel iniPCBItemJPanel = new JPanel(new BorderLayout());

              JPanel iniNamePanel = new JPanel(new GridLayout(4, 1));

              JPanel iniValuePanel = new JPanel(new GridLayout(4, 1));

             

              PIDLabel = new JLabel("PID:");

              requiredTimeLabel = new JLabel("RequiredTime:");

              priorityLabel = new JLabel("Priority:");

              statuesLabel = new JLabel("Statues:");

              iniNamePanel.add(PIDLabel);

              iniNamePanel.add(requiredTimeLabel);

              iniNamePanel.add(priorityLabel);

              iniNamePanel.add(statuesLabel);

             

              PIDTextField = new JTextField("", 10);

              PIDTextField.setEditable(true);

              requiredTimeTextField = new JTextField("", 10);

              requiredTimeTextField.setEditable(true);

              priorityTextField = new JTextField("", 10);

              priorityTextField.setEditable(true);

              statusTextField = new JTextField("", 10);

              statusTextField.setEditable(false);

              iniValuePanel.add(PIDTextField);

              iniValuePanel.add(requiredTimeTextField);

              iniValuePanel.add(priorityTextField);

              iniValuePanel.add(statusTextField);

             

              iniPCBItemJPanel.add(iniNamePanel, BorderLayout.WEST);

              iniPCBItemJPanel.add(iniValuePanel, BorderLayout.CENTER);

              return iniPCBItemJPanel;

       }

       public int readInteger(String s) {

              int num = -1;

              try  {

                     num = Integer.parseInt(s);

                     }  catch(NumberFormatException numberformatexception) {                        

                          statuesTextArea.append("Please input a positive integer!\n");

                          num = -999;

               }     

           return num;

       }

      

       public void addToBackupList(String newID, int s1, int s2, String s) {

                    ProcessPCB item = backupPCB.getItem(newID);

                 if(item != null) {

                        statuesTextArea.append("The PCB " + newID + " has existed in Backup List!\n"

                                      + "you need to modify the PID of the selected PCB!\n");

                        while(item != null) {

                              newID = s + newID;

                              item = backupPCB.getItem(newID);

                  }

                 }

              ProcessPCB newPCB = new ProcessPCB(newID, s1, s2, "Waiting");

              backupPCB.addItem(newPCB);

              backupList.setListData(backupPCB.getItemsProperties());

              backupTotalTextField.setText(Integer.toString(backupPCB.getNumberOfItems()));

       }

      

       public void addToReadyList(String nowID, int s1, int s2, String s) {  

              ProcessPCB item = readyPCB.getItem(nowID);

          if(item != null) {           

                 statuesTextArea.append("The PCB " + nowID + " has existed in Ready List!\n"

                                       + "you need to modify the PID of the selected PCB!\n");

                 while(item != null) {   

                        nowID = s + nowID;

                     item = backupPCB.getItem(nowID);

            }

          }

         ProcessPCB newPCB = new ProcessPCB(nowID, s1, s2, "Ready");

      readyPCB.addItem(newPCB);

      sortReadyPCB();

      readyList.setListData(readyPCB.getItemsProperties());

       }

      

       class AddToBAKListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

                     String newID = PIDTextField.getText();

                     String newTime = requiredTimeTextField.getText();

                     String newPriority = priorityTextField.getText();

                     int s1 = 0, s2 = 0, tag1=-1, tag2=-1;

                    

                     if(newTime != null)

               {                    

                            s1 = readInteger(newTime);

                            if(s1 > 0.0) tag1 = 1;

                   else  statuesTextArea.append("The neededTime must be a positive integer.\n");

               }

                     if(newPriority != null)

               {

                            s2 = readInteger(newPriority); 

                if(s1 != -999) tag2 = 1;

                   else statuesTextArea.append("The priority must be an integer.\n");

               }

                     if(tag1 ==1 && tag2 == 1 ) {

                            if(newID == null)  {

                             statuesTextArea.append("The value of ID mustn't be null!\n");

                     } else {

                            addToBackupList(newID, s1, s2, "B");                

                         statuesTextArea.append("The PCB record item has been added to BackupList!\n");

                         reset();

                     }

                     }     

              }

       }

      

       class AddToReadyListener implements ActionListener {

           public void actionPerformed(ActionEvent event) {

                     String nowID = PIDTextField.getText();

                     String time = requiredTimeTextField.getText();

                     String priority = priorityTextField.getText();

                     int s1 = 0, s2 = 0;

                     int tag1 = -1, tag2 = -1;

                     if(time != null)

               {         

                            s1 = readInteger(time);

                   if(s1 > 0.0)  tag1=1;

                else statuesTextArea.append("The neededTime must be a positive integer.\n");            

               }

                     if(priority != null)

               {

                            s2 = readInteger(priority);

                   if(s2 != -999)  tag2=1;

                else statuesTextArea.append("The priority must be an integer.\n");

               }

               if(tag1 ==1 && tag2 == 1) {

                      if(nowID == null)  {

                             statuesTextArea.append("The value of ID mustn't be null!\n");

                     }  else  {

                            if(readyPCB.getNumberOfItems() < 6)  {

                                          addToReadyList(nowID, s1, s2, "R");

                                       statuesTextArea.append("The student record item has been added to ReadyList!\n");                                                                

                            } else {

                                   statuesTextArea.append("The ReadyList was full! The new ProcessPCB will be added to BackupList!\n");

                                   addToBackupList(nowID, s1, s2, "b");

                                   statuesTextArea.append("The student record item has been added to BackupList!\n");

                            }                                     

                            reset();

                    }

               }      

              }         

       }

       public void reset() {

              PIDTextField.setText("");

              requiredTimeTextField.setText("");

              priorityTextField.setText("");

              statusTextField.setText("");

       }

      

       /**

        * This inner class processes <code>resetButton</code> events.

        */

       class ResetListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

                     reset();

              }

       }

      

       /**

        * This inner class processes <code>suspendButton</code> events.

        */

           //注:在挂起时,不会触发进程调度,而是在点击"startSyatemJButton"时才会出发进程调度

       class SuspendListener implements ActionListener {

              /**

               * Removes an order item from the current order.

               *

               * @param event  the event object.

               */

              public void actionPerformed(ActionEvent event) {

  

                     String selectedReadyItem = null;

                     String pid = "";

                     if(readyPCB.getNumberOfItems() == 0)

            {

                            statuesTextArea.append("The readyList is empty!\n");

            } else {

                   selectedReadyItem = (String) readyList.getSelectedValue();

                if(selectedReadyItem == null)  {

                       statuesTextArea.append("Please select an item from the ready list!\n");

                } else

                {

                       StringTokenizer stringtokenizer = new StringTokenizer(selectedReadyItem, "_");

                             pid = stringtokenizer.nextToken();

                             ProcessPCB selectedItem = readyPCB.getItem(pid);

                       if(selectedItem == null)  {

                              statuesTextArea.append("No student recorditem of Num " + pid + " is founded!\n");

                       }  else  {

                              ProcessPCB boolTtem = suspendedPCB.getItem(pid);

                              if(boolTtem != null) {

                                     statuesTextArea.append("The PCB " + pid + " has existed in Suspend List!\n"

                                           + "you need to modify the PID of the selected PCB!\n");

                                     while(boolTtem != null) {

                                            pid = "X" + pid;

                                            boolTtem = suspendedPCB.getItem(pid);

                                     }

                              }

                              ProcessPCB newPcb = new ProcessPCB(pid, selectedItem.getRequiredTime(),

                                            selectedItem.getPriority(),"Suspended");

                              suspendedPCB.addItem(newPcb);

                              readyPCB.removeItem(selectedItem);

                              sortReadyPCB();  //注意考虑一下

                              suspendList.setListData(suspendedPCB.getItemsProperties());

                              readyList.setListData(readyPCB.getItemsProperties());

                           statuesTextArea.append("The product has been suspended!\n");

                           suspendTotalTextField.setText(Integer.toString(suspendedPCB.getNumberOfItems()));

                        }

                }                      

               }         

        }

       }

      

       public void sortReadyPCB() {

              PCBRecords currentReadyPCB = new PCBRecords();

              int num = readyPCB.getNumberOfItems();

              if(num > 0) {

                     for(int i=num; i>=1; i--) {

                            Iterator readyIterator = readyPCB.iterator();

                            ProcessPCB currentItem = (ProcessPCB) readyIterator.next();

                            for( ; readyIterator.hasNext(); ) {

                                   ProcessPCB nowItem = (ProcessPCB) readyIterator.next();

                                   if(currentItem.getPriority() < nowItem.getPriority()) {

                                          currentItem = null;

                                          currentItem = nowItem;

                                   }     

                            }

                            currentReadyPCB.addItem(currentItem);

                            readyPCB.removeItem(currentItem);

                     }

                     readyPCB = null;

                     readyPCB = currentReadyPCB;

              }            

       }

      

       /**

        * This inner class processes <code>umountButton</code> events.

        */

       class UmountListener implements ActionListener {

              /**

               * Removes an order item from the current order.

               *

               * @param event  the event object.

               */

              public void actionPerformed(ActionEvent event) {

                    

                     String selectedSuspendedItem = null;

                     String id = "";

                     if(suspendedPCB.getNumberOfItems() == 0)

            {

                            statuesTextArea.append("The suspendList is empty!\n");

            } else {

                   selectedSuspendedItem = (String) suspendList.getSelectedValue();

                if(selectedSuspendedItem == null)  {

                       statuesTextArea.append("Please select an item from the suspend list!\n");

                } else

                {

                       StringTokenizer stringtokenizer = new StringTokenizer(selectedSuspendedItem, "_");

                             id = stringtokenizer.nextToken();

                             ProcessPCB selectedItem = suspendedPCB.getItem(id);

                       if(selectedItem == null)  {

                              statuesTextArea.append("No student recorditem of Num " + id + " is founded!\n");

                       }  else  {

                              if(readyPCB.getNumberOfItems() < 6) {

                                    

                                     ProcessPCB selectedToItem = readyPCB.getItem(id);

                                     if(selectedToItem != null) {

                                            statuesTextArea.append("The PCB " + id + "has existed in Ready List! The PID will be modify!\n");

                                            while(selectedToItem != null) {  

                                                   id = id+"X";

                                                   selectedToItem = readyPCB.getItem(id);

                                            }

                                     }

                                     ProcessPCB newToItemPCB = new ProcessPCB(id, selectedItem.getRequiredTime(), selectedItem.getPriority(), "Ready");

                                     readyPCB.addItem(newToItemPCB);

                                     suspendedPCB.removeItem(selectedItem);    

                                     suspendList.setListData(suspendedPCB.getItemsProperties());

                                     suspendTotalTextField.setText(Integer.toString(suspendedPCB.getNumberOfItems()));

                                     sortReadyPCB();   //注意考虑

                                     readyList.setListData(readyPCB.getItemsProperties());

                                  statuesTextArea.append("The product has been Umounted to Ready List!\n");

                              } else {

                                     statuesTextArea.append("The ReadyList was full! The new ProcessPCB will be Umounted to BackupList!\n");

                                     ProcessPCB selectedToItem = backupPCB.getItem(id);

                                     if(selectedToItem != null) {

                                            statuesTextArea.append("The PCB " + id + "has existed in Backup List! The PID will be modify!\n");

                                            while(selectedToItem != null) {                                       

                                                   id = id+"x";

                                                   selectedToItem = backupPCB.getItem(id);

                                            }

                                     }

                                     ProcessPCB newToItemPCB = new ProcessPCB(id, selectedItem.getRequiredTime(), selectedItem.getPriority(), "Waiting");

                                     backupPCB.addItem(newToItemPCB);

                                     suspendedPCB.removeItem(selectedItem);        

                                     suspendList.setListData(suspendedPCB.getItemsProperties());

                                     backupList.setListData(backupPCB.getItemsProperties());

                                     suspendTotalTextField.setText(Integer.toString(suspendedPCB.getNumberOfItems()));

                                  statuesTextArea.append("The product has been Umounted to Backup List!\n");

                           }     

                        }                    

                 }                       

             }

            }

       }

       /**

        * This inner class processes <code>removeButton</code> events.

        */

             

       class RemoveListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

  

                     String selectedRemovsItem = null;

                     String id = "";

                     if(suspendedPCB.getNumberOfItems() == 0)

            {

                            statuesTextArea.append("The record is empty!\n");

            } else

            {

                   selectedRemovsItem = (String) suspendList.getSelectedValue();

                if(selectedRemovsItem == null)  {

                       statuesTextArea.append("The value of ID mustn't be null!\n");

                } else {

                       StringTokenizer stringtokenizer = new StringTokenizer(selectedRemovsItem, "_");

                             id = stringtokenizer.nextToken();

                             ProcessPCB suspendedItem = suspendedPCB.getItem(id);

                       if(suspendedItem == null)  {

                              statuesTextArea.append("No student recorditem of Num " + id + " is founded!\n");

                       }  else  {

                             

                              suspendedPCB.removeItem(suspendedItem);

                              suspendList.setListData(suspendedPCB.getItemsProperties());

                           statuesTextArea.append("The product has been removed!\n");

                           suspendTotalTextField.setText(Integer.toString(suspendedPCB.getNumberOfItems()));

                      }                 

                }              

               }

        }     

       }

  

       public void PCBSchudling() {

              while(readyPCB.getNumberOfItems() < 6) {

                     if(backupPCB.getNumberOfItems() > 0) {

                            Iterator bwackupPCBIterator = backupPCB.iterator();

                            ProcessPCB newItem = (ProcessPCB) bwackupPCBIterator.next();

                            readyPCB.addItem(newItem);

                            backupPCB.removeItem(newItem);

                            //注意考虑要不要排序

                            sortReadyPCB();

                            readyList.setListData(readyPCB.getItemsProperties());

                            backupList.setListData(backupPCB.getItemsProperties());

                            backupTotalTextField.setText(Integer.toString(backupPCB.getNumberOfItems()));

                     } else break;

              }

       }

      

    public void run() {

             

              PCBSchudling();

              if(readyPCB.getNumberOfItems() > 0) {

                     Iterator readyIterator = readyPCB.iterator();

                     ProcessPCB runningItem = (ProcessPCB) readyIterator.next();

                     if(runningItem.getRequiredTime()>0) {

                            runningItem.run();

                            CPUTextArea.append("PCB " + runningItem.getPID() + " is running!\n");

                     }

                     if(runningItem.getRequiredTime() <= 0) {

                            statuesTextArea.append("The work has been finished and the PCB will be moved out from the memory!\n");

                            readyPCB.removeItem(runningItem);

                            runningItem = null;

                            //注意

                            PCBSchudling();

                     }

                     sortReadyPCB();

                     readyList.setListData(readyPCB.getItemsProperties());

              } else {

                     this.systemStatues = 0;

                     System.exit(0);

              }

       }

      

       boolean getSystemStatues() {

              if(this.systemStatues == 1)

                     return true;

              else return false;

       }

      

       class StartSystemListener implements ActionListener {

             

              public void actionPerformed(ActionEvent event) {

                     systemStatues = 1;

                     run();

              }

       }

      

    class SystemPauseListener implements ActionListener {

             

              public void actionPerformed(ActionEvent event) {

                     systemStatues = 2;

              }

       }

   

    class StopSystemListener implements ActionListener {

             

              public void actionPerformed(ActionEvent event) {

                     systemStatues = 3;

              }

       }

   

    class ResetSystemListener implements ActionListener {

             

              public void actionPerformed(ActionEvent event) {

                     systemStatues = 0;

              }

       }

    class priotiryListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

                   timeslice = 1;

            }

    }

    class timeslicListener implements ActionListener {

           public void actionPerformed(ActionEvent event) {

                  timeslice = getTimesliceText();

                  if(timeslice <= 0) {

                         statuesTextArea.append("The timeslice must be a positive integer!\n");

                         timesliceJtf.setText("1");

                         timeslice = 1;

                  }

           }

    }

    public int getTimesliceText() {

           int n;

           try  {

                     n = Integer.parseInt(timesliceJtf.getText());

                     }  catch(NumberFormatException numberformatexception) {                        

                          statuesTextArea.append("The timeslice must be a positive integer!\n");

                          n = -999;

               }

           return n;

    }

}

01版(精简版)

MemoryItem.java

package src;

public class MemoryItem {

       private int memoryBase=0;

       private int memoryLimit=0;

       private int availableStatus=0;

      

       public MemoryItem(int initMemoryBase, int initMemoryLimit) {

              this.memoryBase = initMemoryBase;

              this.memoryLimit = initMemoryLimit;

       }

      

       public int getMemoryBase() {

              return this.memoryBase;

       }

  

    public int getMemoryLimit() {

              return this.memoryLimit;

       }

    

    public int getStatus() {

              return this.availableStatus;

       }

   

    public String toString() {

           return this.getMemoryBase() + "_" + this.getMemoryLimit() + "\n";

    }

   

}

ProcessPCB.java

package src;

public class ProcessPCB {

//     backupBAK 后备  ready 就绪  suspend 挂起 memory内存

       private String PID;

       private int RequiredTime;

       private int Priority;

       private String Status;

       private int MwmoryBase = 0000;

       private int MemoryLimit;

//     private String PCBPointer;

       public ProcessPCB(String initpID, int initRTime, int initpriority,

                                String status, int initBase, int initLimit) {

             

              this.PID = initpID;

              this.RequiredTime = initRTime;

              this.Priority = initpriority;

              this.Status = status;

              this.MwmoryBase = initBase;

              this.MemoryLimit = initLimit;

       }

      

       public String getPID() {

              if(this.PID == null)

                     return " ";

              else

                     return this.PID;

       }

      

       public int getRequiredTime() {

              return this.RequiredTime;

       }

       public int getPriority() {

              return this.Priority;

       }

      

       public String getStatus() {

              if(this.Status == null)

                     return " ";

              else

                     return this.Status;

       }

       public int getMemoryBase() {

              return this.MwmoryBase;

       }

       public int getMemoryLimit() {

              return this.MemoryLimit;

       }

       public boolean equals(ProcessPCB  pcb) {

             

              if(pcb.getPID() == this.getPID())  {

                     return true;

              }

              else return false;

       }

      

       public String toString() {

              return this.getPID() + "_" + this.getRequiredTime() + "_" + this.getPriority() + "_"

                       + this.getStatus() + "_" + this.getMemoryBase() + "_" + this.getMemoryLimit() + "\n";

       }

      

       public void run() {

              this.RequiredTime = this.RequiredTime-1;

              this.Priority = this.Priority-1;

       }

      

}

PCBRecords.java

package src;

import java.util.ArrayList;

import java.util.Iterator;

public class PCBRecords implements Iterable<ProcessPCB> {

      

       private ArrayList<ProcessPCB> PCBItems;

      

    public ArrayList<ProcessPCB> getPCBItems() {

              return this.PCBItems;

       }

   

    public PCBRecords() {

              this.PCBItems = new ArrayList<ProcessPCB>();

       }

   

    public void addItem(ProcessPCB PcbItem) {

              this.PCBItems.add(PcbItem);

       }

   

    public void removeItem(ProcessPCB PCbItem) {

             this.PCBItems.remove(PCbItem);

      }

   

    public ProcessPCB getItem(ProcessPCB processPCB) {     

             for (ProcessPCB pCbItem : this.PCBItems) {

                              if (pCbItem.equals(processPCB)) {                                  

                                      return pCbItem;

                                  }

                            }                         

                     return null;

      }

     

    public ProcessPCB getItem(String pid) {    

             for (ProcessPCB pcBItem : this.PCBItems) {

                              if (pcBItem.getPID().equals(pid)) {                                 

                                      return pcBItem;

                                  }

                            }                         

                     return null;

      }

   

    public int getNumberOfItems() { 

             return this.PCBItems.size();

      }

    public String[] getItemsProperties() {  

             String itemsProperties[] = new String[getNumberOfItems()];

            

             int i = 0;

        for(Iterator iterator1 = PCBItems.iterator(); iterator1.hasNext();)

        {

               ProcessPCB stu_Item = (ProcessPCB)iterator1.next();

               itemsProperties[i++] = stu_Item.toString();

        }

        return itemsProperties;

      }

       public Iterator<ProcessPCB> iterator() {

              return this.PCBItems.iterator();

       }

}

MemoryRecords.java

package src;

import java.util.ArrayList;

import java.util.Iterator;

public class MemoryRecords implements Iterable<MemoryItem> {

       private ArrayList<MemoryItem> memoryItems;

       public Iterator<MemoryItem> iterator() {

              // TODO Auto-generated method stub

              return this.memoryItems.iterator();

       }

    public ArrayList<MemoryItem> getMemoryItems() {

             

              return this.memoryItems;

       }

   

    public MemoryRecords() {

           this.memoryItems = new ArrayList<MemoryItem>();

    }

   

    public void addItem(MemoryItem newMemoryItem) {

           this.memoryItems.add(newMemoryItem);

    }

    public void removeItem(MemoryItem momoryItem) {

           this.memoryItems.remove(momoryItem);

    }

   

    public MemoryItem getMomoryItem(MemoryItem item) {

           for(MemoryItem mItem : this.memoryItems) {

                  if(mItem.equals(item)) {

                         return mItem;

                  }

           }

           return null;

    }

    public MemoryItem getMemoryItem(int base) {

           for(MemoryItem mItem : this.memoryItems) {

                  if(mItem.getMemoryBase() == base) {

                         return mItem;

                  }

           }

           return null;

    }

   

    public int getNumberOfItems() {        

             return this.memoryItems.size();

      }

   

    public String[] getItemsProperties() {

           String itemsProperties[] = new String[getNumberOfItems()];

           int i=0;

           for(Iterator iterator1 = this.memoryItems.iterator(); iterator1.hasNext(); ) {

                  MemoryItem mmItem = (MemoryItem) iterator1.next();

                  itemsProperties[i++] = mmItem.toString();

           }

           if(itemsProperties == null) {

                  itemsProperties[0] = "      ";

           }

           return itemsProperties;

    }

}

SingleCPUSchedulingGUI03.java

package src;

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

import src.SingleCPUSchedulingGUI03.AddToBAKListener;

import src.SingleCPUSchedulingGUI03.AddToReadyListener;

import src.SingleCPUSchedulingGUI03.DisplayBackupProcessListener;

import src.SingleCPUSchedulingGUI03.DisplaySuspendedProcessListener;

import src.SingleCPUSchedulingGUI03.DisplayreadyProcessListener;

import src.SingleCPUSchedulingGUI03.RemoveListener;

import src.SingleCPUSchedulingGUI03.ResetListener;

import src.SingleCPUSchedulingGUI03.ResetSystemListener;

import src.SingleCPUSchedulingGUI03.StartSystemListener;

import src.SingleCPUSchedulingGUI03.SuspendListener;

import src.SingleCPUSchedulingGUI03.UmountListener;

//import src.myframe.MyWindowMonitor;

import java.io.*;

import java.text.*;

public class SingleCPUSchedulingGUI03 extends JFrame {

       /* Standar error stream */

       static private PrintWriter  stdErr = new  PrintWriter(System.err, true);

      

       static private int WIDTH = 800, HEIGHT = 750;            // the size of the Frame 主面板                                             

       /* 各列表对应的面板规格*/

/*    对应各名词释义  backupBAK 后备  ready 就绪  suspend 挂起  memory内存  */

       static private int BackupBAK_CELL_SIZE = 250, BackupBAK_LIST_ROWS = 10;       //后备队列

       static private int Suspend_CELL_SIZE = 250, Suspend_LIST_ROWS = 10;         //挂起队列

       static private int Ready_CELL_SIZE = 200, Ready_LIST_ROWS = 6;              //就绪队列

       static private int Memory_CELL_SIZE = 200, Memory_LIST_ROWS = 10;       //内存队列

       static private int CPU_ROWS = 12, CPU_COLS = 22;                         //CPU面板

       static private int STATUS_ROWS = 8, STATUS_COLS = 30;                   //系统状态面板

    private int timeslice = 1;                              //设置时间片大小

    private int systemStatus=0;        //设置系统状态 0——系统预备状态,等待开始,1——系统运行状态,2——系统暂停状态

       static private int TOTAL__TEXTFIELD_SIZE = 10;       // Size total text field 记录各队列元素个数

      

       private JList backupList, suspendList, readyList, memoryList;  //各队列相对应的数组列表

     //   进程添加框中的"添加至后备队列","添加至就绪队列","重置"Button

       private JButton addToBAKButton, addToReadyButton, resetButton;

          //就绪队列框中的"挂起",挂起队列框中的"解挂","删除"Button

       private JButton suspendButton, umountButton, removeButton;

              //Status面板中的"启动系统","重置系统"Button

       private JButton startButton, pauseButton, resetSyatemButton;  

                   //优先级和时间片单选钮及时间片显示框

       private JRadioButton priorityJRB, timesliceJRB;

       private JLabel timesliceSizeLabel;   

       private JTextField timesliceJtf;

            //后备面板、进程添加面板、挂起面板、内存面板

       private JPanel backupBAKPanel, PCBItemPanel, suspendedPanel, memoryPanel;

                      //后备队列、挂起队列元素总数标签

       private JLabel backupTotalLabel, suspendTotalLabel;

    //进程信息标签  进程编号PID,所需运行时间requiredTime,优先级priority,当前状态statues,内存中的基址base,所需内存大小limit

       private JLabel PIDLabel, requiredTimeLabel, priorityLabel, statuesLabel, baseLabel, limitLabel;

            //后备队列、挂起队列元素总数文本框(不可编辑)

       private JTextField backupTotalTextField, suspendTotalTextField;

       //进程信息文本框 PID(可编辑),requiredTime(可编辑),priority(可编辑),status(不可编辑),base(不可编辑),limit(可编辑)

       private JTextField PIDTextField, requiredTimeTextField, priorityTextField, statusTextField, baseTextField, limitTextField;

            //CPU状态显示文本域(不可编辑),status信息文本域(用于现实程序每一步的操作和影响,不可编辑)

       private JTextArea CPUTextArea, statuesTextArea;

       //后备队列PCB数组,就绪、挂起,——内存(可分分区表)

       PCBRecords backupPCB, readyPCB, suspendedPCB;

       private MemoryRecords memoryItems;

      

       private boolean flag = false;

//main函数

       public static void main(String[] args) throws IOException {

              new SingleCPUSchedulingGUI03().initFrame();

       }

       //初始化Frame

       public void initFrame() {

             

              backupList = new JList();

              backupList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

              backupList.setVisibleRowCount(BackupBAK_LIST_ROWS);

              backupList.setFixedCellWidth(BackupBAK_CELL_SIZE);       

              suspendList = new JList();

              suspendList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

              suspendList.setVisibleRowCount(Suspend_LIST_ROWS);

              suspendList.setFixedCellWidth(Suspend_CELL_SIZE);            

              readyList = new JList();

              readyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

              readyList.setVisibleRowCount(Ready_LIST_ROWS);

              readyList.setFixedCellWidth(Ready_CELL_SIZE);    

              memoryList = new JList();

              memoryList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

              memoryList.setVisibleRowCount(Memory_LIST_ROWS);

              memoryList.setFixedCellWidth(Memory_CELL_SIZE);

             

              suspendButton = new JButton("Suspend");

              addToBAKButton = new JButton("AddToBAK");

              addToReadyButton = new JButton("AddToReady");

              resetButton = new JButton("Reset");

              umountButton = new JButton("Umount");

              removeButton = new JButton("Remove");

              startButton = new JButton("StartSchuliding");

              pauseButton = new JButton("Pause");

              resetSyatemButton = new JButton("ResetSystem");

              priorityJRB = new JRadioButton("Priority", true);

              timesliceJRB = new JRadioButton("Timeslice");

      

              backupTotalLabel = new JLabel("Total:");

              backupTotalTextField = new JTextField("0", TOTAL__TEXTFIELD_SIZE);

              backupTotalTextField.setEditable(false);

              suspendTotalLabel = new JLabel("Total:");

              suspendTotalTextField = new JTextField("0", TOTAL__TEXTFIELD_SIZE);

              suspendTotalTextField.setEditable(false);

              timesliceSizeLabel = new JLabel("Timeslice");

              timesliceJtf = new JTextField("3", 5);

              timesliceJtf.setEditable(true);

             

              CPUTextArea = new JTextArea(CPU_ROWS, CPU_COLS);

              CPUTextArea.setEditable(false);

              statuesTextArea = new JTextArea(STATUS_ROWS, STATUS_COLS);

              statuesTextArea.setEditable(false);

             

/* north panel*/

              JPanel northPanel = new JPanel(new GridLayout(1, 3));   

              // ProcessPCB item information Panel

              PCBItemPanel = new JPanel(new BorderLayout());

              PCBItemPanel.setBorder(

                            BorderFactory.createTitledBorder("PCBItem Information"));

             

              JPanel PCBItemButtonJPanel = new JPanel(new GridLayout(3, 1));

              PCBItemButtonJPanel.add(addToBAKButton);

              PCBItemButtonJPanel.add(addToReadyButton);

              PCBItemButtonJPanel.add(resetButton);

             

              PCBItemPanel.add(this.initPCBItemPanel(), BorderLayout.CENTER);

              PCBItemPanel.add(PCBItemButtonJPanel, BorderLayout.SOUTH);

             

           //backupBAKList Panel

              backupBAKPanel = new JPanel(new BorderLayout());

              backupBAKPanel.setBorder(BorderFactory.createTitledBorder("BackupList"));

             

        JPanel backupTotalPAnel = new JPanel();

        backupTotalPAnel.add(backupTotalLabel);

        backupTotalPAnel.add(backupTotalTextField);

        backupBAKPanel.add (

                            new JScrollPane(backupList,

                                          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                                          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);

        backupBAKPanel.add(backupTotalPAnel, BorderLayout.SOUTH);

           // SuspendList Panel     

        suspendedPanel = new JPanel(new BorderLayout());

        suspendedPanel.setBorder(BorderFactory.createTitledBorder("SuspendList"));

       

        JPanel suspendedTotalPAnel = new JPanel();

        suspendedTotalPAnel.add(suspendTotalLabel);

        suspendedTotalPAnel.add(suspendTotalTextField);

                                             

        JPanel suspendComponentPanel = new JPanel(new GridLayout(1, 2));

        suspendComponentPanel.add(umountButton);

        suspendComponentPanel.add(removeButton);

       

        suspendedPanel.add (suspendedTotalPAnel, BorderLayout.NORTH);

        suspendedPanel.add (

                            new JScrollPane(suspendList,

                                          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                                          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);

        suspendedPanel.add(suspendComponentPanel, BorderLayout.SOUTH);

     

        northPanel.add(backupBAKPanel);

        northPanel.add(PCBItemPanel);

        northPanel.add(suspendedPanel);

             

/* center Panel*/ 

        JPanel centrelPanel = new JPanel(new GridLayout(1, 3));

           

            // readyList panel

        JPanel readyListPanel = new JPanel(new BorderLayout());

        readyListPanel.setBorder(BorderFactory.createTitledBorder("ReadyList"));

        readyListPanel.add (

                         new JScrollPane(readyList,

                                       JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                                       JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));

        readyListPanel.add (suspendButton, BorderLayout.SOUTH);

            // CPU panel

        JPanel CPUPanel = new JPanel();

        CPUPanel.setBorder(BorderFactory.createTitledBorder("CPU"));

        CPUPanel.add (new JScrollPane(CPUTextArea,

                         JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                         JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));

        memoryPanel = new JPanel(new BorderLayout());

        memoryPanel.setBorder(BorderFactory.createTitledBorder("MemoryList"));

        memoryPanel.add (

                         new JScrollPane(memoryList,

                                       JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                                       JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));

        centrelPanel.add(readyListPanel);

        centrelPanel.add(CPUPanel);

        centrelPanel.add(memoryPanel);   

/*statues panel*/

        JPanel southPanel = new JPanel(new BorderLayout());

       

        JPanel statuesPanel = new JPanel();

        statuesPanel.setBorder(BorderFactory.createTitledBorder("Statues"));

        statuesPanel.add (new JScrollPane(statuesTextArea,

                         JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,

                         JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));

       

        JPanel systemContralButtonPanel = new JPanel(new GridLayout(6, 1));

        systemContralButtonPanel.setBorder(BorderFactory.createTitledBorder("systemContral"));

        ButtonGroup group = new ButtonGroup();

        group.add(priorityJRB);

        group.add(timesliceJRB);

        JPanel porityPanel = new JPanel(new GridLayout(1, 2));

        porityPanel.add(timesliceSizeLabel);

        porityPanel.add(timesliceJtf);

        systemContralButtonPanel.add(priorityJRB);

        systemContralButtonPanel.add(timesliceJRB);

        systemContralButtonPanel.add(porityPanel);

        systemContralButtonPanel.add(startButton);

        systemContralButtonPanel.add(pauseButton);

        systemContralButtonPanel.add(resetSyatemButton);

       

        southPanel.add(statuesPanel, BorderLayout.CENTER);

        southPanel.add(systemContralButtonPanel, BorderLayout.EAST);

     

//            arrange panels in window

              setLayout(new BorderLayout());

              add(northPanel, BorderLayout.NORTH);

              add(centrelPanel, BorderLayout.CENTER);       

              add(southPanel, BorderLayout.SOUTH);  //statuesPanel

             

//            start listening for list and buttons events

              backupList.addListSelectionListener(new DisplayBackupProcessListener());

              suspendList.addListSelectionListener(new DisplaySuspendedProcessListener());

              readyList.addListSelectionListener(new DisplayreadyProcessListener());

                           

              addToBAKButton.addActionListener(new AddToBAKListener());

              addToReadyButton.addActionListener(new AddToReadyListener());

              resetButton.addActionListener(new ResetListener());

              suspendButton.addActionListener(new SuspendListener());

              umountButton.addActionListener(new UmountListener());

              removeButton.addActionListener(new RemoveListener());

              startButton.addActionListener(new StartSystemListener());

              pauseButton.addActionListener(new SystemPauseListener());

              resetSyatemButton.addActionListener(new ResetSystemListener()); 

              priorityJRB.addActionListener(new priotiryListener());

              timesliceJRB.addActionListener(new timeslicListener());

             

              backupPCB = new PCBRecords();

              readyPCB = new PCBRecords();

              suspendedPCB = new PCBRecords();

              memoryItems = new MemoryRecords();

              MemoryItem initMemoryItem = new MemoryItem(0,3000);

              memoryItems.addItem(initMemoryItem);

              backupList.setListData(backupPCB.getItemsProperties());

              readyList.setListData(readyPCB.getItemsProperties());

              suspendList.setListData(suspendedPCB.getItemsProperties());

              memoryList.setListData(memoryItems.getItemsProperties());

             

              this.setTitle("CPUSchudling");

              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

              this.setSize(WIDTH, HEIGHT);

              this.setResizable(true);

              this.setVisible(true);

              this.setLocation(200, 10);

              this.addWindowListener(new MyWindowMonitor());

       }

      

      

      

       public JPanel initPCBItemPanel() {

             

              JPanel iniPCBItemJPanel = new JPanel(new BorderLayout());

              JPanel iniNamePanel = new JPanel(new GridLayout(6, 1));

              JPanel iniValuePanel = new JPanel(new GridLayout(6, 1));

             

              PIDLabel = new JLabel("PID:");

              requiredTimeLabel = new JLabel("RequiredTime:");

              priorityLabel = new JLabel("Priority:");

              statuesLabel = new JLabel("Statues:");

              baseLabel = new JLabel("Base:");

              limitLabel = new JLabel("Limit:");

              iniNamePanel.add(PIDLabel);

              iniNamePanel.add(requiredTimeLabel);

              iniNamePanel.add(priorityLabel);

              iniNamePanel.add(statuesLabel);

              iniNamePanel.add(baseLabel);

              iniNamePanel.add(limitLabel);

             

              PIDTextField = new JTextField("", 10);

              PIDTextField.setEditable(true);

              requiredTimeTextField = new JTextField("", 10);

              requiredTimeTextField.setEditable(true);

              priorityTextField = new JTextField("", 10);

              priorityTextField.setEditable(true);

              statusTextField = new JTextField("", 10);

              statusTextField.setEditable(false);

              baseTextField = new JTextField("", 10);

              baseTextField.setEditable(false);

              limitTextField = new JTextField("", 10);

              limitTextField.setEditable(true);

              iniValuePanel.add(PIDTextField);

              iniValuePanel.add(requiredTimeTextField);

              iniValuePanel.add(priorityTextField);

              iniValuePanel.add(statusTextField);

              iniValuePanel.add(baseTextField);

              iniValuePanel.add(limitTextField);

             

              iniPCBItemJPanel.add(iniNamePanel, BorderLayout.WEST);

              iniPCBItemJPanel.add(iniValuePanel, BorderLayout.CENTER);

             

              return iniPCBItemJPanel;

       }

      

       class MyWindowMonitor extends WindowAdapter {

              public void windowClosing(WindowEvent e) {

                     System.exit(0);

                     setVisible(false);

              }

       }    

        

       public void displayInformation(ProcessPCB pcb) {

             

              PIDTextField.setText(pcb.getPID());

              requiredTimeTextField.setText(Integer.toString(pcb.getRequiredTime()));

              priorityTextField.setText(Integer.toString(pcb.getPriority()));

              statusTextField.setText(pcb.getStatus());

              baseTextField.setText(Integer.toString(pcb.getMemoryBase()));

              limitTextField.setText(Integer.toString(pcb.getMemoryLimit()));

       }

       //Displays the information of the selected PCBItem

       class DisplayBackupProcessListener implements ListSelectionListener {

             

              public void valueChanged(ListSelectionEvent event) {

                     if (! backupList.getValueIsAdjusting()) {              

                            String id = null, selectedBAKItem = null;

                            selectedBAKItem = (String) backupList.getSelectedValue();

                            if(selectedBAKItem  != null) {

                                   StringTokenizer stringtokenizer = new StringTokenizer(selectedBAKItem, "_");

                                   id = stringtokenizer.nextToken();                              

                                   ProcessPCB backupItem = backupPCB.getItem(id);

                                   if(backupItem != null)

                                   {

                                          displayInformation(backupItem);

                                   }

                                   statuesTextArea.append(backupItem.toString() + "ProcessItem " + id

                                                          + "in backupList has been displayed!\n");

                            }

                     }

              }

       }

      

       class DisplaySuspendedProcessListener implements ListSelectionListener {

              public void valueChanged(ListSelectionEvent event) {

                     if (! suspendList.getValueIsAdjusting()) {

//                          stdErr.flush();

                            String id = "";

                            String str = (String) suspendList.getSelectedValue();

                            if(str != null) {

                                   StringTokenizer strtokenizer = new StringTokenizer(str, "_");

                                   id = strtokenizer.nextToken();                                  

                                   ProcessPCB selectedSuspendedItem = suspendedPCB.getItem(id);

                                   if(selectedSuspendedItem != null)

                                   {

                                          displayInformation(selectedSuspendedItem);

                                   }                                

                                   statuesTextArea.append(selectedSuspendedItem.toString() + "ProcessItem " + id

                                                          + "in suspendList has been displayed!\n");

                            }

                     }

              }

       }

       class DisplayreadyProcessListener implements ListSelectionListener {

              public void valueChanged(ListSelectionEvent event) {

                     if (! readyList.getValueIsAdjusting()) {             

                            String id = null, s = null;

                            s = (String) readyList.getSelectedValue();

                            if(s != null) {

                                   StringTokenizer sttokenizer = new StringTokenizer(s, "_");

                                   id = sttokenizer.nextToken();

                                   ProcessPCB readyItem = readyPCB.getItem(id);

                                   if(readyItem != null)

                                   {

                                          displayInformation(readyItem);

                                   }

                                   statuesTextArea.append(readyItem.toString() + "ProcessItem " + id

                                                          + "in readyList has been displayed!\n");

                            }     

                     }

              }

       }

          //内存可分分区表排序,按可用内存大小降序排列

       public void sortMemoryList() {

              MemoryRecords currentListItems = new MemoryRecords();

              int num = memoryItems.getNumberOfItems();

              if(num>0)  {

                     for(int i=num; i>=1; i--) {

                            Iterator memoryIterator = memoryItems.iterator();

                            MemoryItem currentItem = (MemoryItem) memoryIterator.next();

                            for( ; memoryIterator.hasNext(); ) {

                                   MemoryItem nowItem = (MemoryItem) memoryIterator.next();

                                   if(currentItem.getMemoryLimit() < nowItem.getMemoryLimit()) {

                                          currentItem = null;

                                          currentItem = nowItem;

                                   }    

                            }

                            currentListItems.addItem(currentItem);

                            memoryItems.removeItem(currentItem);

                     }

                     memoryItems = null;

                     memoryItems = currentListItems; 

              }

              memoryList.setListData(memoryItems.getItemsProperties());

       }

         //判断能否为进程分配内存

       public boolean boolMemoryAllocation(int neededLimit) {

              if(memoryItems.getNumberOfItems()>0) {

                     Iterator memoryListIteartor = memoryItems.iterator();

                     MemoryItem lagerestItem = (MemoryItem) memoryListIteartor.next();

                     if(lagerestItem.getMemoryLimit()>= neededLimit)

                            return true;

                     else {

                            return false;

                     }                         

              } else {

                     return false;

              }                  

       }

       //内存分配,按最先适应算法原则

       public int MemoryAllocation(int neededLimit) {

              int currentBase=-1, currentLimit=-1;

              Iterator memoryListIteartor = memoryItems.iterator();

              MemoryItem lagerestItem = (MemoryItem) memoryListIteartor.next();

              currentBase = lagerestItem.getMemoryBase()+neededLimit;

              currentLimit = lagerestItem.getMemoryLimit()-neededLimit;

              memoryItems.removeItem(lagerestItem);

              if(currentLimit>0) {

                     memoryItems.addItem(new MemoryItem(currentBase, currentLimit));

              }

              sortMemoryList();

              return lagerestItem.getMemoryBase();

       }

       //内存回收

       public void memoryRecall(int nowBase, int nowLimit) {

              MemoryItem recallItem = null;

              int recalledBase = nowBase;

              int recalledLimit = nowLimit;

              if(memoryItems.getNumberOfItems()>0) {

                     Iterator memoryListIteartor = memoryItems.iterator();

                     for( ;memoryListIteartor.hasNext(); ) {

                            MemoryItem existedItem = (MemoryItem) memoryListIteartor.next();

                            if(existedItem.getMemoryBase() == (nowBase+nowLimit)) {

                                   recalledLimit = recalledLimit+existedItem.getMemoryLimit();

                                   memoryItems.removeItem(existedItem);     

                                   memoryListIteartor = memoryItems.iterator();

                            } else if(nowBase == (existedItem.getMemoryBase()+existedItem.getMemoryLimit())) {

                                   recalledBase = existedItem.getMemoryBase();

                                   recalledLimit = recalledLimit+existedItem.getMemoryLimit();

                                   memoryItems.removeItem(existedItem);

                                   memoryListIteartor = memoryItems.iterator();

                            }                                                     

                            //memoryListIteartor = memoryItems.iterator();  //注意此处代码曾引发异常

                     }

                     //recallItem = new MemoryItem(recalledBase, recalledLimit); //曾产生异常

              }

              recallItem = new MemoryItem(recalledBase, recalledLimit);

              memoryItems.addItem(recallItem);

              sortMemoryList(); 

       }

      

       public int readInteger(String s) {

              int num = -1;

              try  {

                     num = Integer.parseInt(s);

                     }  catch(NumberFormatException numberformatexception) {                       

                          statuesTextArea.append("Please input a positive integer!\n");

                          num = -999;

               }    

           return num;

       }

      

       public void addToBackupList(String newID, int s1, int s2, int s3, String s) {

                    ProcessPCB item = backupPCB.getItem(newID);

                 if(item != null) {

                        statuesTextArea.append("The PCB " + newID + " has existed in Backup List!\n"

                                      + "you need to modify the PID of the selected PCB!\n");

                        while(item != null) { 

                              newID = s + newID;

                              item = backupPCB.getItem(newID);

                  }

                 }

              ProcessPCB newPCB = new ProcessPCB(newID, s1, s2, "Waiting", -1, s3);

              backupPCB.addItem(newPCB);

              backupList.setListData(backupPCB.getItemsProperties());

              backupTotalTextField.setText(Integer.toString(backupPCB.getNumberOfItems()));

       }

      

       public void addToReadyList(String nowID, int s1, int s2, int s3, String s) {     

              ProcessPCB item = readyPCB.getItem(nowID);

          if(item != null) {             

                 statuesTextArea.append("The PCB " + nowID + " has existed in Ready List!\n"

                                       + "you need to modify the PID of the selected PCB!\n");

                 while(item != null) {    

                        nowID = s + nowID;

                     item = backupPCB.getItem(nowID);

            }

          }

        int s4=MemoryAllocation(s3);

         sortMemoryList();

         ProcessPCB newPCB = new ProcessPCB(nowID, s1, s2, "Ready", s4, s3);

      readyPCB.addItem(newPCB);

      sortReadyPCB();      

       }

      

       class AddToBAKListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

                     String newID = PIDTextField.getText();

                     String newTime = requiredTimeTextField.getText();

                     String newPriority = priorityTextField.getText();

                     String newLimit = limitTextField.getText();

                     int s1 = 0, s2 = 0, s3 = 0, tag1=-1, tag2=-1, tag3=-1;

                    

                     if(newTime != null)

               {                   

                            s1 = readInteger(newTime);

                            if(s1 > 0.0) tag1 = 1;

                   else  statuesTextArea.append("The neededTime must be a positive integer.\n");

               }

                     if(newPriority != null)

               {

                            s2 = readInteger(newPriority); 

                if(s1 != -999) tag2 = 1;

                   else statuesTextArea.append("The priority must be an integer.\n");

               }

                     if(newLimit != null)

               {

                            s3 = readInteger(newLimit);

                            if(s3 > 0.0) tag3 = 1;

                   else statuesTextArea.append("The neededLimit must be a positive integer.\n");

               }

                     if(tag1 ==1 && tag2 == 1 && tag3 == 1) {

                            if(newID == null)  {

                             statuesTextArea.append("The value of ID mustn't be null!\n");

                     } else {

                            addToBackupList(newID, s1, s2, s3, "B");

                         statuesTextArea.append("The PCB recorditem has been added to BackupList!\n");

                         reset();

                     }

                     }    

              }

       }

      

       class AddToReadyListener implements ActionListener {

           public void actionPerformed(ActionEvent event) {

                     String nowID = PIDTextField.getText();

                     String time = requiredTimeTextField.getText();

                     String priority = priorityTextField.getText();

                     String limit = limitTextField.getText();

                     int s1 = 0, s2 = 0, s3 =0;

                     int tag1 = -1, tag2 = -1, tag3 = -1;

                     if(time != null)

               {        

                            s1 = readInteger(time);

                   if(s1 > 0.0)  tag1=1;

                else statuesTextArea.append("The neededTime must be a positive integer.\n");             

               }

                     if(priority != null)

               {

                            s2 = readInteger(priority);

                   if(s2 != -999)  tag2=1;

                else statuesTextArea.append("The priority must be an integer.\n");

               }

                     if(limit != null)

               {          

                            s3 = readInteger(limit);

                   if(s3 > 0.0)  tag3=1;

                else statuesTextArea.append("The neededLimit must be a positive integer.\n");

               }

               if(tag1 ==1 && tag2 == 1 && tag3 ==1) {

                      if(nowID == null)  {

                             statuesTextArea.append("The value of ID mustn't be null!\n");

                     }  else  {

         //                 PCBItem item = null;

                            if(readyPCB.getNumberOfItems() < 6)  {

                                   if(boolMemoryAllocation(s3)) {

                                          addToReadyList(nowID, s1, s2, s3, "R");

                                       statuesTextArea.append("The student recorditem has been added to ReadyList!\n");

                                   } else {

                                          statuesTextArea.append("No memory available! The PCB will be added to backupList!\n");

                                          addToBackupList(nowID, s1, s2, s3, "b");

                                          statuesTextArea.append("The student recorditem has been added to BackupList!\n");

                                   }                                                                     

                            } else {

                                   statuesTextArea.append("The ReadyList was full! The new ProcessPCB will be added to BackupList!\n");

                                   addToBackupList(nowID, s1, s2, s3, "b");

                                   statuesTextArea.append("The student recorditem has been added to BackupList!\n");

                            }                                     

                            reset();

                    }

               }      

              }        

       }

      

       public void reset() {

              PIDTextField.setText("");

              requiredTimeTextField.setText("");

              priorityTextField.setText("");

              statusTextField.setText("");

              baseTextField.setText("");

              limitTextField.setText("");

             

       }

        // This inner class processes resetButton events. 

       class ResetListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

                     reset();

              }

       }

        // This inner class processes suspendButton events.

           //注:在挂起时,不会触发进程调度,而是在点击"startSyatemJButton"时才会出发进程调度

       class SuspendListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {  

              String selectedReadyItem = null;

              String pid = "";

              if(readyPCB.getNumberOfItems() == 0)

        {

                     statuesTextArea.append("The readyList is empty!\n");

        } else {

              try {

                   selectedReadyItem = (String) readyList.getSelectedValue();

                if(selectedReadyItem == null)  {

                     statuesTextArea.append("Please select an item from the ready list!\n");

                } else

                   {

                           StringTokenizer stringtokenizer = new StringTokenizer(selectedReadyItem, "_");

                                 pid = stringtokenizer.nextToken();

                                 ProcessPCB selectedItem = readyPCB.getItem(pid);

                           if(selectedItem == null)  {

                                  statuesTextArea.append("No student recorditem of Num " + pid + " is founded!\n");

                           }  else  {

                                  ProcessPCB boolItem = suspendedPCB.getItem(pid);

                                  if(boolItem != null) {

                                         statuesTextArea.append("The PCB " + pid + " has existed in Suspend List!\n"

                                               + "you need to modify the PID of the selected PCB!\n");

                                         while(boolItem != null) {

                                                pid = "S" + pid;

                                                boolItem = suspendedPCB.getItem(pid);

                                         }

                                  }

                                    //注意下一步存在问题!                            

                                  ProcessPCB newPcb = new ProcessPCB(pid, selectedItem.getRequiredTime(),

                                                selectedItem.getPriority(),"Suspended", -1, selectedItem.getMemoryLimit());                                

                                  memoryRecall(selectedItem.getMemoryBase(), selectedItem.getMemoryLimit());

                                  suspendedPCB.addItem(newPcb);

                                  readyPCB.removeItem(selectedItem);

//                                if(systemStatues == 1) {

//                                       PCBSchudling();

//                                }

                                  sortReadyPCB();

                                  suspendList.setListData(suspendedPCB.getItemsProperties());

                               statuesTextArea.append("The product has been suspended!\n");

                               suspendTotalTextField.setText(Integer.toString(suspendedPCB.getNumberOfItems()));

                            }

                    } 

                   } catch (RuntimeException e1) {

                                // TODO Auto-generated catch block

                         }                                           

               }         

        }

       }

                        //对Ready队列进行优先级排序

       public void sortReadyPCB() {

              PCBRecords currentReadyPCB = new PCBRecords();

              int num = readyPCB.getNumberOfItems();

              if(num > 0) {

                     for(int i=num; i>=1; i--) {

                            Iterator readyIterator = readyPCB.iterator();

                            ProcessPCB currentItem = (ProcessPCB) readyIterator.next();

                            for( ; readyIterator.hasNext(); ) {

                                   ProcessPCB nowItem = (ProcessPCB) readyIterator.next();

                                   if(currentItem.getPriority() < nowItem.getPriority()) {

                                          currentItem = null;

                                          currentItem = nowItem;

                                   }    

                            }

                            currentReadyPCB.addItem(currentItem);

                            readyPCB.removeItem(currentItem);

                     }

                     readyPCB = null;

                     readyPCB = currentReadyPCB;

              }

              readyList.setListData(readyPCB.getItemsProperties());

       }

        // This inner class processes umountButton events.

       class UmountListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {                  

                     String selectedSuspendedItem = null;

                     String id = "";

                     if(suspendedPCB.getNumberOfItems() == 0)

            {

                            statuesTextArea.append("The suspendList is empty!\n");

            } else {

                   try {

                          selectedSuspendedItem = (String) suspendList.getSelectedValue();

                    if(selectedSuspendedItem == null)  {

                           statuesTextArea.append("Please select an item from the suspend list!\n");

                    } else

                    {

                           StringTokenizer stringtokenizer = new StringTokenizer(selectedSuspendedItem, "_");

                                 id = stringtokenizer.nextToken();

                                 ProcessPCB selectedItem = suspendedPCB.getItem(id);

                           if(selectedItem == null)  {

                                  statuesTextArea.append("No student recorditem of Num " + id + " is founded!\n");

                           }  else  {

                                  int s3 = selectedItem.getMemoryLimit();

                                  if(readyPCB.getNumberOfItems() < 6) {                                                                          

                                         if(boolMemoryAllocation(s3)) {

                                                addToReadyList(id, selectedItem.getRequiredTime(),

                                                                      selectedItem.getRequiredTime(), s3, "r");

                                                            statuesTextArea.append("The product has been Umounted to Ready List!\n");

                                         } else {

                                                statuesTextArea.append("No memory available! The PCB will be Umounted to BackupList!\n");

                                                addToBackupList(id, selectedItem.getRequiredTime(),

                                                                       selectedItem.getRequiredTime(), s3, "II");                                       

                                          statuesTextArea.append("The product has been Umounted to Backup List!\n");

                                         }

                                        

                                  } else {

                                         statuesTextArea.append("The ReadyList was full! The new ProcessPCB will be Umounted to BackupList!\n");

                                         addToBackupList(id, selectedItem.getRequiredTime(),

                                                  selectedItem.getRequiredTime(), s3, "II");

                                      statuesTextArea.append("The product has been Umounted to Backup List!\n");

                               }

                                  suspendedPCB.removeItem(selectedItem);       

                                                 suspendList.setListData(suspendedPCB.getItemsProperties());

                                                 suspendTotalTextField.setText(Integer.toString(suspendedPCB.getNumberOfItems()));

                            }                   

                     }

                      } catch (RuntimeException e1) {

                                // TODO Auto-generated catch block

                         }                                             

             }

            }

       }

       /**

        * This inner class processes <code>removeButton</code> events.

        */

             

       public int getTimeslice() {    

              return timeslice;

       }

       class RemoveListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

  

                     String selectedRemovsItem = null;

                     String id = "";

                     if(suspendedPCB.getNumberOfItems() == 0)

            {

                            statuesTextArea.append("The record is empty!\n");

            } else

            {

                   selectedRemovsItem = (String) suspendList.getSelectedValue();

                if(selectedRemovsItem == null)  {

                       statuesTextArea.append("The value of ID mustn't be null!\n");

                } else {

                       StringTokenizer stringtokenizer = new StringTokenizer(selectedRemovsItem, "_");

                             id = stringtokenizer.nextToken();

                             ProcessPCB suspendedItem = suspendedPCB.getItem(id);

                       if(suspendedItem == null)  {

                              statuesTextArea.append("No student recorditem of Num " + id + " is founded!\n");

                       }  else  {

                             

                              suspendedPCB.removeItem(suspendedItem);

                              suspendList.setListData(suspendedPCB.getItemsProperties());

                           statuesTextArea.append("The product has been removed!\n");

                        }

                       suspendTotalTextField.setText(Integer.toString(suspendedPCB.getNumberOfItems()));

                }                     

               }

        }     

       }

                   //内存进程调度

       public void PCBSchudling() {

              while(readyPCB.getNumberOfItems() < 6) {

                     if(backupPCB.getNumberOfItems() > 0) {

                            Iterator bwackupPCBIterator = backupPCB.iterator();

                            ProcessPCB newItem = (ProcessPCB) bwackupPCBIterator.next();

                            readyPCB.addItem(newItem);

                            backupPCB.removeItem(newItem);

                            sortReadyPCB();

                            readyList.setListData(readyPCB.getItemsProperties());

                            backupList.setListData(backupPCB.getItemsProperties());

                            backupTotalTextField.setText(Integer.toString(backupPCB.getNumberOfItems()));

                     } else break;

              }

       }

/*   

    public void run() {

             

              PCBSchudling();

              if(readyPCB.getNumberOfItems() > 0) {

                     Iterator readyIterator = readyPCB.iterator();

                     PCBItem runningItem = (PCBItem) readyIterator.next();

                     if(runningItem.getPCB().getRequiredTime()>0) {

                            runningItem.run();

                     }

                     if(runningItem.getPCB().getRequiredTime() <= 0) {

                            statuesTextArea.append("The work has been finished and the PCB will be moved out from the memory!\n");

                            readyPCB.removeItem(runningItem);

                            runningItem = null;

                            //注意

                            PCBSchudling();

                     }

                     sortReadyPCB();

                     readyList.setListData(readyPCB.getItemsProperties());

              } else {

                     statuesTextArea.append("CPU backlssh/race!\n");

              //     System.exit(0);

              }

       }

*/

       class RunThread extends Thread {

              int t, TimeSlice;

              boolean Flag = true;

              public void run(){

                     while(Flag) { 

                            //Warning!!!!!!!!!!!!                          

                            if(getSystemStatus() == 0) {

                                   Flag = false;

                                   break;

                            } else if(getSystemStatus() == 2) {

                                   while(getSystemStatus() == 2) {

                                          try {

                                                 Thread.sleep(1000);

                                          } catch (Exception ee) {

                                                 ee.printStackTrace();

                                          }

                                   }

                            }

                           

                            if(readyPCB.getNumberOfItems() < 6) {

                                   if(backupPCB.getNumberOfItems() > 0) {

                                          while(readyPCB.getNumberOfItems() < 6) {

                                                 if(backupPCB.getNumberOfItems() > 0) {

                                                        Iterator bwackupPCBIterator = backupPCB.iterator();

                                                        ProcessPCB newItem = (ProcessPCB) bwackupPCBIterator.next();

                                                        while(bwackupPCBIterator.hasNext() ) {

                                                               int s = newItem.getMemoryLimit();

                                                               if (boolMemoryAllocation(s)) {

                                                                      break;

                                                               } else

                                                                      newItem = (ProcessPCB) bwackupPCBIterator.next();       

                                                               if(newItem == null) break;

                                                        }

                                                        if(newItem != null) {

                                                               int bbase=0;

                                                               int llimit = newItem.getMemoryLimit();

                                                               bbase = MemoryAllocation(llimit);

                                                               ProcessPCB nowItem  = new ProcessPCB(newItem.getPID(), newItem.getRequiredTime(), newItem.getPriority(),

                                                                                                                    "Ready", bbase, llimit);

                                                               readyPCB.addItem(nowItem);

                                                               backupPCB.removeItem(newItem);

                                                               backupList.setListData(backupPCB.getItemsProperties());

                                                               backupTotalTextField.setText(Integer.toString(backupPCB.getNumberOfItems()));

                                                        } else {

                                                               statuesTextArea.append("No memory available!\n");

                                                               break;

                                                        }                                                                                               

                                                 } else break;

                                          }

                                   }

                            }

                            sortReadyPCB();

                            backupList.setListData(backupPCB.getItemsProperties());

                            backupTotalTextField.setText(Integer.toString(backupPCB.getNumberOfItems()));

                            Iterator readyIterator = readyPCB.iterator();

                            ProcessPCB runningItem = null;

                            if(readyIterator.hasNext()) {

                                   runningItem = (ProcessPCB) readyIterator.next();

                            }

                            //PCBItem runningItem = (PCBItem) readyIterator.next(); //readyPCB.getNumberOfItems() > 0

                            //注意此处有bug结果就出现了java.util.NoSuchElementException的错误提示 ,就是黄色的那一句,多了一个 迭代器的next()。

                            if(runningItem != null) {

                                  

                                   t = runningItem.getRequiredTime();

                                   TimeSlice = getTimeslice();

                                   System.out.println(TimeSlice);

                                   for(int i=TimeSlice; i>=0; i--) {

                                          if(t >= 0) {

                                                 runningItem.run();

                                                 t--;

                                                 sortReadyPCB();

                                                 if(getFlag() == true)

                                                        CPUTextArea.append("The PCB " + runningItem.getPID() + " is running!\n");

                                                 try {

                                                        Thread.sleep(990);

                                                 } catch (Exception ee) {

                                                        ee.printStackTrace();

                                                 }

                                          }                                       

                                   }                                                            

                                  

                                   if(t < 0) {

                                          Flag = false;

                                          statuesTextArea.append("The work has been finished and the PCB will be moved out from the memory!\n");

                                          memoryRecall(runningItem.getMemoryBase(), runningItem.getMemoryLimit());

                                          readyPCB.removeItem(runningItem);

                                          runningItem = null;

                                          sortReadyPCB();

                                   }

                                   if(readyPCB.getNumberOfItems() > 0)

                                          Flag = getFlag();

                                   else Flag = false;

                            } else Flag = false;

                            //Warning!!!!!!!!!!!!!!!!

                            if(getSystemStatus() == 0) {

                                   Flag = false;

                                   break;

                            } else {

                                   if(getSystemStatus() == 2) {

                                          while(getSystemStatus() == 2) {

                                                 try {

                                                        Thread.sleep(1000);

                                                 } catch (Exception ee) {

                                                        ee.printStackTrace();

                                                 }

                                          }

                                   }

                                   if(getSystemStatus() == 1) Flag = true;

                            }                  

                     }    

              }

       }

       public boolean getFlag() {

              return this.flag;

       }

      

       public int getSystemStatus() {

              return systemStatus;

       }

      

       class StartSystemListener implements ActionListener {

             

              public void actionPerformed(ActionEvent event) {

                     if(readyPCB.getNumberOfItems() > 0) {

                            if(systemStatus == 0) {

                                   Thread runThread = new RunThread();

                                   flag = true;

                                   runThread.start();

                                   systemStatus = 1;

                                   statuesTextArea.append("System Start!\n");

                            } else {

                                   statuesTextArea.append("Operat False!\n");

                            }    

                     } else statuesTextArea.append("The ReadyList is empty! Please add processes\n");

                             

              }

       }

      

       class SystemPauseListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

                     if(systemStatus == 1) {

                            flag = false;

                            systemStatus = 2;

                            pauseButton.setText("Coutinue");

                            statuesTextArea.append("System Pause!\n");

                     }  else if(systemStatus == 2) {

                            flag = true;

                            systemStatus = 1;

                            pauseButton.setText("Pause");

                            statuesTextArea.append("System Continue!\n");

                     } else {

                            statuesTextArea.append("Operat False!\n");

                     }           

              }

       }

    class ResetSystemListener implements ActionListener {

             

              public void actionPerformed(ActionEvent event) {

                     if(systemStatus != 0) {

                            flag = false;

                   systemStatus = 0;

                   backupPCB = null;          

                   readyPCB = null;

                   suspendedPCB = null;

                   memoryItems = null;

                   backupPCB = new PCBRecords();

                         readyPCB = new PCBRecords();

                         suspendedPCB = new PCBRecords();

                         backupList.setListData(backupPCB.getItemsProperties());

                         readyList.setListData(readyPCB.getItemsProperties());

                         suspendList.setListData(suspendedPCB.getItemsProperties());

                        

                         backupTotalTextField.setText("0");

                         suspendTotalTextField.setText("0");

                         CPUTextArea.setText("");

                   statuesTextArea.setText(""); 

                   priorityJRB.doClick();

                   timeslice = 1;

                   timesliceJtf.setText("3");

                   memoryItems = new MemoryRecords();

                         memoryList.removeAll();

                         MemoryItem newMemoryItem = new MemoryItem(0,3000);

                   memoryItems.addItem(newMemoryItem);

                   memoryList.setListData(memoryItems.getItemsProperties());

                   statuesTextArea.append("System Reset!\n");

                     } else {

                            statuesTextArea.append("Operat False!\n");

                     }

              }

       }

   

    class priotiryListener implements ActionListener {

              public void actionPerformed(ActionEvent event) {

                   timeslice = 1;

            }

    }

    class timeslicListener implements ActionListener {

           public void actionPerformed(ActionEvent event) {

                  timeslice = getTimesliceText();

                  if(timeslice <= 0) {

                         statuesTextArea.append("The timeslice must be a positive integer!\n");

                         timesliceJtf.setText("1");

                         timeslice = 1;

                  }

           }

    }

   

    public int getTimesliceText() {

           int n;

           try  {

                     n = Integer.parseInt(timesliceJtf.getText());

                     }  catch(NumberFormatException numberformatexception) {                       

                          statuesTextArea.append("The timeslice must be a positive integer!\n");

                          n = -999;

               }

           return n;

    }

}


 [FHLC1]Pause和reset暂时失效,将在实验2中完成;

 [FHLC2]此技术是参阅资料和高手的代码学来的,本人将在第二期的代码分析和评估中给出,并郑重声明、尊重原著的知识产权!

 [FHLC3]初学get和set方法,总以为都要用;但在本设计中没用到,只是摆设

更多相关推荐:
操作系统进程调度实验报告

操作系统进程调度实验报告一实验目的用高级语言编写和调试一个进程调度程序以加深对进程的概念及进程调度算法的解进程调度时进程管理的主要内容之一通过设计编制调试一个简单的进程调度模拟系统对进程调度进程运行状态变换加深...

计算机操作系统进程调度实验报告

操作系统实验题设计一若干并发进程的进程调度程序一实验目的无论是批处理系统分时系统还是实时系统用户进程数一般都大于处理机数这将导致用户进程互相争夺处理机这就要求进程调度程序按一定的策略动态地把处理及分配给处于就绪...

操作系统进程调度实验报告

实验一进程调度实验专业XXXXX学号XXXXX姓名XXX实验日期20XX年XX月XX日一实验目的通过对进程调度算法的模拟加深对进程概念和进程调度算法的理解二实验要求编写程序实现对5个进程的调度模拟要求至少采用两...

操作系统实验进程调度

实验二进程调度实验内容进程调度模拟实验实验目的通过模拟进程调度算法了解进程调度的过程并比较不同的调度算法的区别实验题目设计一段程序来模拟优先级调度算法和时间片轮转算法要求可以指定进程的数量各进程需要CPU的时间...

操作系统进程调度模拟程序实验报告

目录1课程设计目的32课程设计要求33相关知识34需求分析45概要设计56详细设计67测试修改及运行结果138参考文献159结束语1510附件1511课程设计的目的理解操作系统进程管理中进行进程调度的过程和编程...

操作系统进程调度实验报告

计算机操作系统课程实验报告题目实验一进程调度计算机学院计算机科学与技术学院专业姓班学名级号20xx年10月21日1实验一进程调度1实验目的通过对进程调度算法的模拟进一步理解进程的基本概念加深对进程运行状态和进程...

操作系统进程调度实验报告

实验报告课程名称计算机操作系统实验名称班级学号姓名成绩指导教师赵安科实验日期20xx年5月21日一实验题目进程及其管理二实验内容设计一个简单的进程调度算法模拟OS中的进程调度过程三实验要求进程数不少于5个进程调...

操作系统实验报告-进程调度算法的实现

南昌大学实验报告4进程调度算法的实现学生姓名张虹学号6100409033专业班级电091班实验类型验证综合设计创新实验日期实验成绩一实验目的通过实验加强对进程调度算法的理解和掌握二实验内容编写程序实现进程调度算...

操作系统实验报告:设计一若干并发进程的进程调度程序

操作系统实验报告操作系统实验题设计一若干并发进程的进程调度程序一实验目的无论是批处理系统分时系统还是实时系统用户进程数一般都大于处理机数这将导致用户进程互相争夺处理机这就要求进程调度程序按一定的策略动态地把处理...

11级操作系统_进程模拟调度实验报告

操作系统实验报告单说明仅作参考请勿雷同一实验目的在采用多道程序设计的系统中往往有若干个进程同时处于就绪状态当就绪进程个数大于处理器数时就必须依照某种策略来决定哪些进程优先占用处理器本实验模拟在单处理器情况下的处...

操作系统C 进程调度算法实验报告

华北科技学院计算机系综合性实验实验报告课程名称操作系统C实验学期20xx至20xx学年第2学期学生所在系部计算机系年级20xx专业班级网络B10学生姓名学号任课教师杜杏菁实验成绩计算机系制华北科技学院计算机系综...

操作系统模拟实验:单处理机系统的进程调度实验报告

数学与计算机学院单处理机系统的进程调度实验报告年级07学号20xx429023姓名王阳成绩专业信计实验地点主楼402指导教师王硕实验项目单处理机系统的进程调度实验日期实验报告要求一实验目的1加深对进程概念的理解...

操作系统进程调度实验报告(37篇)