0

这是我的代码。正如您在 run 方法中看到的,我将值分配给 tStart、tEnd、tAround 和 wTime。但是当线程结束时,它们仍然具有-1的默认值。我尝试在 run() 运行时打印出它们的值,并且我有正确的值。但是当线程结束时,它们并没有将这些值“写入”回变量。

public class PCB extends Thread{
    public int id, arrivalTime, cpuBurst, ioBurst;
    public int tStart, tEnd, tAround, wTime;
    public PCB(){
        id = -1;
        arrivalTime = -1;
        cpuBurst = -1;
        ioBurst = -1;

        tStart = -1;
        tEnd = -1;
        tAround = -1;
        wTime = -1;
    }

 public void run(){
        try{
    .........

            //calculation for FCFS 
            if (id == 1){ //special case for the first one
                tStart = arrivalTime;
            }
            else tStart = lastEndTime;

            tEnd = tStart + cpuBurst + ioBurst;
            tAround = tEnd - arrivalTime;
            wTime = tStart - arrivalTime;

                            PCBThreadStopFlag = true;   

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

当线程结束时,这就是我打印值的方式:

        // now we print out the process table
    String format = "|P%1$-10s|%2$-10s|%3$-10s|%4$-10s|%5$-10s|%6$-10s|%7$-10s|%8$-10s|\n";
    System.out.format(format, "ID", "ArrTime", "CPUBurst", "I/OBurst", "TimeStart", "TimeEnd","TurnAround","WaitTime");
    ListIterator<PCB> iter = resultQueue.listIterator();
    while(iter.hasNext()){
        PCB temp = iter.next();
        System.out.format(format, temp.id, temp.arrivalTime, temp.cpuBurst, temp.ioBurst, temp.tStart, temp.tEnd, temp.tAround, temp.wTime );
    }

这是我等待线程首先停止的方式:

while(!rq.values.isEmpty()){
            //System.out.println("Ready queue capacity now: " + rq.values.size());
            currentProcess = new PCB(rq.values.getFirst());
            currentProcess.start();

            while(PCBThreadStopFlag == false) {}
            //currentProcess.stop();
            PCBThreadStopFlag = false;

            //after everything is done, remove the first pcb
            // and add it to the result queue (just to print the report)
            resultQueue.addLast(rq.values.removeFirst());           
        }

我在 run() 顶部使用标志 PCBThreadStopFlag(在所有分配完成后最后)然后在这个函数中,我使用 while(PCBThreadStopFlag == false) {} 来执行“忙等待”任务。可能是这个原因??

4

1 回答 1

3

这只是一个猜测,但我敢打赌,在打印结果之前您不会加入线程。换句话说,我怀疑您正在启动线程,然后立即打印结果,而无需等待线程完成。

编辑:好的,试试这个......

想法 #1:将 PCBThreadStopFlag 声明为 volatile,然后重试。告诉我们这是否有效。

想法#2:完全摆脱整个停止标志的事情,并将忙碌的等待替换为

currentProcess.join();

并告诉我们这是否有效。

于 2009-11-01T05:39:47.477 回答