我正在尝试模拟一个任务管理器,我可以在其中创建线程并查看它们的运行情况。线程不会增加超过 1。
这是我的实体中的 run 方法。
@Override
public void run() {
if(this.GetRuntime() == 0)
Active = true;
this.SetRuntime(this.GetRuntime() + 1);
try {
ProcessThread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
这是我运行线程的开关情况。
switch(command)
{
case 1:
System.out.println("Process PID: ");
int pid = in.nextInt();
System.out.println("Process name: ");
String name = in.next();
System.out.println("Process memory: ");
int memory = in.nextInt();
ProcessThread newProcess = new ProcessThread(pid, name, memory);
if(memory > freeMemory) {
System.out.println("There is not enough memory available\n\n");
break;
}
freeMemory -= newProcess.getMemory();
newProcess.start();
//processService.RunProcess(newProcess, freeMemory);
processList.add(newProcess);
break;
case 5:
for(int i = 0; i < processList.size(); i++) {
ProcessThread currentProcess = processList.get(i);
System.out.println(currentProcess.getProcessName() + "has been running for " +
currentProcess.GetRuntime() + "s - consuming " +
currentProcess.getMemory() + " MB");
}
System.out.println(freeMemory + " MB left.\n\n");
break;
}
当给出命令 5 时,结果应该是: Thread-1 已运行 5 秒 - 消耗 100MB
我的所有线程都返回 1 秒的运行时间。
最佳答案
您的线程 hibernate 了 10 秒而不是 1 秒。
更改ProcessThread.sleep(10000);
至ProcessThread.sleep(1000);
并且您需要在运行时实现中使用一个循环,正如其他使用者所评论的那样
关于java - 线程计数器在第一个刻度后不会增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56006495/