我想创建一个比较器来操作,以便具有较低到达时间的进程将首先出现在排序中,如果两个进程具有相同的到达时间,则具有较低进程 id 的进程首先出现在排序中。我尝试了以下代码,但似乎不起作用。有没有人看到它的缺陷?
public class FCFSComparator implements Comparator<Process>
{
public int compare(Process o1, Process o2)
{
int result = o1.getArrivalTime() - o2.getArrivalTime();
if(result == 0)
{
return (o1.getPid() < o2.getPid()) ? -1 : 1;
}
else
{
return result;
}
// return (result != 0 ? result : o1.getPid() - o2.getPid());
}
}
Run Code Online (Sandbox Code Playgroud)
具体来说,给定过程如下
pid = 0 arrival time = 10
pid = 1 arrival time = 30
pid = 2 arrival time = 15
pid = 3 arrival time = 15
pid = 4 arrival time = 66
Run Code Online (Sandbox Code Playgroud)
我在最后得到以下顺序
Pid = 0 arrival time = 10
Pid = 2 arrival time = 15
Pid = 1 arrival time = 30
Pid = 4 arrival time = 66
Pid = 3 arrival time = 15
Run Code Online (Sandbox Code Playgroud)
我找不到你的比较器有什么问题。这是我的测试用例:
public class TestComparator {
static class Process {
int pid;
int arrivalTime;
Process(int pid, int arrivalTime) {
this.pid = pid;
this.arrivalTime = arrivalTime;
}
@Override
public String toString() {
return "Process [pid=" + pid + ", arrivalTime=" + arrivalTime + "]";
}
}
static class FCFSComparator implements Comparator<Process> {
public int compare(Process o1, Process o2) {
int result = o1.arrivalTime - o2.arrivalTime;
if (result == 0) {
return (o1.pid < o2.pid) ? -1 : 1;
} else {
return result;
}
}
}
public static void main(String[] args) {
List<Process> processes = Arrays.asList(
new Process(0, 10),
new Process(1, 30),
new Process(2, 15),
new Process(3, 15),
new Process(4, 66));
Collections.sort(processes, new FCFSComparator());
for (Process process : processes) {
System.out.println(process);
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Process [pid=0, arrivalTime=10]
Process [pid=2, arrivalTime=15]
Process [pid=3, arrivalTime=15]
Process [pid=1, arrivalTime=30]
Process [pid=4, arrivalTime=66]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14210 次 |
| 最近记录: |