调度算法常见于操作系统,因为系统的资源时有限的,当有多个进程(或多个进程发出的请求)要使用系统资源时,就需要按照一定的原则来选择进程(请求)来占用系统资源。这就是所谓的调度。常见的调度算法有以下几种
1,先来先服务(FCFS)
1)概述
先来先服务,就是按照请求的提交时间顺序,依次执行。
2)实现
定义一个task作为任务实例,BlockingQueue作为任务队列
package com.xieq.algorithm.schedule;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Description
*
* @author qiang.xie02
* @date 2022/1/18 14:08
*/
public class FCFS {
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue<Task> queue = new LinkedBlockingQueue<>();
new Thread(() -> {
while (true) {
try {
Task task = queue.take();
task.exec();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
for (int i = 1; i <= 5; i++) {
System.out.println("add task" + i);
Task task = new Task("task" + i, (long) new Random().nextInt(1000));
queue.put(task);
}
}
}
class Task {
/**
* 任务名称
*/
private String name;
/**
* 任务执行耗时
*/
private Long execTime;
/**
* 任务添加时间
*/
private Long addTime;
public Task(String name, Long execTime) {
this.name = name;
this.execTime = execTime;
this.addTime = System.currentTimeMillis();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getExecTime() {
return execTime;
}
public void setExecTime(Long execTime) {
this.execTime = execTime;
}
public Long getAddTime