在Java程序中跟踪时间

时间:2012-10-19 14:03:27

标签: java time linked-list

我要做的是让一个进程(这只是一个对象)具有如下的certiant值:

public String name;
public int priority; //not to exceed 4
public int serviceTimeTotal; //holds the cumlitive service time
public int waitTimeTotal; //holds the cumulative wait time
public int arrivalTime;
public int burstTime;
public boolean added;
public boolean active;
public boolean isDone;

我想跟踪每个进程获得服务的时间以及每个进程等待其他进程获得服务的时间。我不知道我是否正确跟踪时间我想要的时间是毫秒,我认为这是什么,我使用.nanoTime当我运行它运行的程序但是等待时间根本没有增加但是正在运行的那个的服务时间确实增加了所以我认为我的那个正确 所以这就是我如何做到这一点

   public static void runLevelOne(LinkedList<MyProcess> ll, MyProcess mp)
{
    int start = 0;

    mp.active = true;
   System.out.println("Running Level One Queue");
    //runs for 3 millseconds
    while(start <= 3000)
    {
        //cheak to see if process is over
       if(mp.burstTime <= mp.serviceTimeTotal)
        {
            mp.isDone = true;
            System.out.println(mp.name + " has completed its task");
            mp.active = false;
            //get rid of it from the queue
            ll.remove(mp);
            break;

        }


        try {
            //run proccess
            Thread.sleep(3);
        } catch (InterruptedException ex) {
            Logger.getLogger(PartATwo.class.getName()).log(Level.SEVERE, null, ex);
        }


        start += System.nanoTime()/ 1000000;
        mp.serviceTimeCalculator(start);
        mp.calculatePriority();
        //make all other proccesses in ll wait
        for(MyProcess s :ll)
        {
            s.waiting(start);
            System.out.println(s.name+  " wait time: " + s.waitTimeTotal);
        }
        System.out.println(mp.name + " new priority is: " + mp.priority);
    }
    mp.active = false;

}

这将运行该过程,然后计算链表中每个进程的服务时间,优先级和等待时间。

在MyProcess类中,我像这样计算优先级

public int calculatePriority()
{
    System.out.println("Starting Priority " + priority);
    System.out.println("service time " + serviceTimeTotal);
    System.out.println("waitTimeTotal " + waitTimeTotal);

    priority = (serviceTimeTotal + waitTimeTotal) / serviceTimeTotal;
    if(priority <= 1.5)
    {
        priority = 1;
    }
    if(priority > 1.6 && priority <= 2.5 )
    {
        priority = 2;
    }
    if(priority > 2.6 && priority <= 3.5)
    {
        priority = 3;
    }
    if(priority > 3.6 && priority > 3.5)
    {
        priority = 4;
    }
    return priority;
}

和这样的服务时间和等待时间

  public  void waiting(int time)
{
    if(active = false)
    {
        waitTimeTotal += time;
    }
}
 public void serviceTimeCalculator(int time)
{
    serviceTimeTotal += time;
}

这种接缝应该可以工作,但事实并非如此。我在这里错过了什么 感谢您对此的任何帮助

1 个答案:

答案 0 :(得分:1)

首先,使用long代替int来保存时间值,即使您将它们分开也是如此。

然后,您还需要使用System.getNanos()设置开始时间,而不是将其设置为0。做类似的事情:

long start = System.getNanos() / 1000000;
long end = start;
while (end - start < 3000) {
    ...
    end = System.getNanos() / 1000000;
}
相关问题