如何对此代码实施SJF调度?

时间:2016-10-25 05:51:56

标签: java operating-system

我正在开发使用操作系统概念安排作业的打印机代码。我接受到达时间和要打印的页数。我使用了信号量,因此一次只能打印一份作业。如何实现SJF调度? 这是我的代码:

import java.util.*;
import java.util.concurrent.Semaphore;
public class newproj{
    static boolean b=true;
    public static Semaphore s = new Semaphore(1);
    public static void main(String[] args){

        Scanner sc=new Scanner(System.in);
        int n;
        System.out.println("Enter number of print jobs:");
        n=sc.nextInt();
        int a[][]=new int[n][2];
        System.out.println("Enter number of pages of each job and arrival time:");
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<2;j++)
            {
                a[i][j]=sc.nextInt();
            }
        }

        Thread[] threads = new Thread[n];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new user(i,a[i][0],a[i][1],s));
            threads[i].start();
        }
    }
}

    class user extends Thread{
    int a,i=0;
    int n,t,ct=0;
    Semaphore s;
    String st;
    public user(int n,int a,int t,Semaphore s)
    {
        this.n=n;
        this.a=a;
        this.s=s;
        this.t=t;
        //System.out.println(this.n);
    }
    public void run()
    {
    while(true)
        {
            synchronized(this){
            if((newproj.b==true)&&(ct>=t))
            {
            try{
                s.acquire();
                newproj.b=false;
                }
            catch(Exception e){}
                System.out.println("Printing "+a+" pages of Job "+(n+1)+" "+(ct++));
                try{
                    for(int j=1;j<=a;j++)
                        System.out.println("Printed "+j+" page of Job "+(n+1)+" "+(ct++));
                    Thread.sleep(1000);
                    }
            catch(Exception e){}
            System.out.println("Job "+(n+1)+" has finished printing "+(ct++));
            newproj.b=true;
            s.release();
            try{
                Thread.sleep(1000);
                }
            catch(Exception e){}
            break;
            }
            else if((newproj.b==false)&&(ct>t))
            {
            System.out.println("Job "+(n+1)+" is waiting"+(ct++));
            try{
                Thread.sleep(1000);
                }
            catch(Exception e){}                
            }
            else if(ct<t)
            {
            System.out.println("No Job to be executed"+(n+1)+" "+(ct++));
            try{
                Thread.sleep(1000);
                }
            catch(Exception e){}                                
            }
            }
            }
        };

}

0 个答案:

没有答案