磁盘调度算法java
时间: 2023-12-06 20:38:18 浏览: 101
Java操作系统磁盘调度算法
磁盘调度算法是操作系统中的一个重要概念,它是指操作系统对于磁盘上的数据进行访问时,按照一定的规则来安排磁盘的读写顺序,以提高磁盘的访问效率。下面是两种常见的磁盘调度算法的Java实现:
1.先来看最短时间优先算法(SSTF)的Java实现:
```java
public class SSTF {
public static void main(String[] args) {
int[] queue = {55, 58, 39, 18, 90, 160, 150, 38, 184};
int head = 50;
int sum = 0;
int[] flag = new int[queue.length];
for (int i = 0; i < queue.length; i++) {
int min = Integer.MAX_VALUE;
int index = 0;
for (int j = 0; j < queue.length; j++) {
if (flag[j] == 0) {
int distance = Math.abs(queue[j] - head);
if (distance < min) {
min = distance;
index = j;
}
}
}
flag[index] = 1;
sum += min;
head = queue[index];
}
System.out.println("SSTF算法磁盘移动的总磁道数为:" + sum);
}
}
```
2.再来看扫描算法(SCAN)的Java实现:
```java
public class SCAN {
public static void main(String[] args) {
int[] queue = {55, 58, 39, 18, 90, 160, 150, 38, 184};
int head = 50;
int sum = 0;
int direction = 1; // 1表示向右,-1表示向左
Arrays.sort(queue);
int index = Arrays.binarySearch(queue, head);
if (index < 0) {
index = -index - 1;
}
while (true) {
if (direction == 1) {
for (int i = index; i < queue.length; i++) {
sum += Math.abs(queue[i] - head);
head = queue[i];
}
direction = -1;
index--;
} else {
for (int i = index; i >= 0; i--) {
sum += Math.abs(queue[i] - head);
head = queue[i];
}
direction = 1;
index++;
}
if (index < 0 || index == queue.length) {
break;
}
}
System.out.println("SCAN算法磁盘移动的总磁道数为:" + sum);
}
}
```
阅读全文