在java中,我不能在线程扩展类的run()函数中为变量赋值

7y4bm7vi  于 2021-07-05  发布在  Java
关注(0)|答案(1)|浏览(336)

这是我的密码。正如您在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){}来执行“busy wait”任务。也许这就是原因??

bvjxkvbb

bvjxkvbb1#

这只是一个猜测,但我敢打赌,在打印结果之前,您没有加入线程。换句话说,我怀疑您正在启动线程,然后在不等待线程完成的情况下立即打印结果。
编辑:好的,试试这个。。。
想法1:将pcbthreadstopflag声明为volatile,然后重试。告诉我们这样行不行。
想法二:彻底摆脱停止标志的事情,把忙碌的等待换成等待

currentProcess.join();

告诉我们这样行不行。

相关问题