操作系统实验 Java

作系统实验项目开发声明:
    1,本人是java初学者,菜鸟级别,发此贴谨以和其他java初学者交流经验,并希望有高手不吝赐教;
    2,本贴公分两期,第一期为项目的开发和实验的完成,主要介绍本人在开发过程中的想法和实现过程;第二期为代码分析和项目评估,主要是通过对比本人作品和其他作者作品,浅谈这一次实验的感受和经验,进一步探究java项目开发流程和技术问题;
    3,第二期中会引用他人的代码,一些是由本人网上下载得来,另一些由同学传送,来源不甚详细,这里郑重声明,本人尊重原著的知识产权,这里引用,纯粹是为了叫深入研究作者的代码规范和编程思想;若原著见此贴,望予以理解!
    4,此次实验只是本人学习过程中的一次较系统的学习,虽然本人尚属菜鸟,但本着诚实做人的原则,保证所有代码均是学校课程学习后的成果,一些尚不熟悉的知识技巧且有参考的地方,也是在深入理解的基础上编写的,绝不会有直接拷贝的情况,这主要是对原著的尊重,和对自己的负责!
    5,因本人时间安排的原因,第二期内容的发帖可能会滞后,特此声明!

 

 

操作系统实验

第一期     项目开发实现

实验名称         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语言面对对象程序设计的特点,实验设计为ProcessPCBMemoryItem类封装PCB和所分配的内存各自的属性与方法;用ProcessRecordsMemoryRecords类封装数组方法;用SingleCPUScheduling实现GUI界面显示;

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

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

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

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

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

           对于实验一,界面如下:

      以上由SingleCPUScheduling001.java(另需ProcessPCB.javaPCBRdecords.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;

    }

}


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

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

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

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值