我需要写一个多线程版本的TaskSchedular
TaskScheduler {
TaskScheduler(List<Task> tasks)
....
}
interface Task {
int getPriority()
void execute()
}
这样就保证了高优先级的任务永远不会在低优先级之后开始执行。
这是我的单线程版本示例。我需要创建这个多线程。
public class SingleThreadedTaskScheduler {
private ExecutorService executorService = Executors.newFixedThreadPool(1);
private PriorityQueue<Task> taskQueue;
private static final PriorityComparator PRIORITY_COMPARATOR = new PriorityComparator();
public SingleThreadedTaskScheduler(List<Task> tasks){
this.taskQueue = new PriorityQueue<Task>(tasks.size(), PRIORITY_COMPARATOR);
this.taskQueue.addAll(tasks);
}
public void executeAllByPriority(){
executorService.submit(new Runnable() {
@Override
public void run() {
for (Task task : taskQueue) {
task.execute();
}
}
});
}
public void executeAllByPriorityWithUnInterruptableFirst(){
executorService.submit(new Runnable() {
@Override
public void run() {
PriorityQueue<Task> interruptedQueue = new PriorityQueue<Task>(taskQueue.size(),PRIORITY_COMPARATOR);
for (Task task : taskQueue) {
if (task instanceof Interruptible && ((Interruptible) task).isInterrupted() ){
interruptedQueue.add(task);
} else {
task.execute();
}
}
for (Task task : interruptedQueue ){
task.execute();
}
}
});
}
@Override
protected void finalize() throws Throwable {
super.finalize();
executorService.shutdown();
}
}
小代码会有很大帮助。