[英]in Java, I can't assign values to variables while i'm in the run() function of a thread-extended class
这是我的代码。 如您在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){}来执行“忙碌等待”任务。 可能这是原因吗?
这只是一个猜测,但是我敢打赌,在打印结果之前,您没有加入线程。 换句话说,我怀疑您正在启动线程,然后立即打印结果,而无需等待线程完成。
编辑:好的,试试这个...
想法1:将PCBThreadStopFlag声明为volatile,然后重试。 告诉我们是否可行。
想法2:完全摆脱整个停止标志,然后将忙碌等待替换为
currentProcess.join();
并告诉我们是否可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.