ScheduledExecutorService
本身并不提供直接设置任务优先级的方法
以下是一个使用 PriorityBlockingQueue
实现的示例:
Runnable
类,其中包含一个表示优先级的字段:public class PriorityRunnable implements Runnable, Comparable<PriorityRunnable> {
private int priority;
private Runnable task;
public PriorityRunnable(int priority, Runnable task) {
this.priority = priority;
this.task = task;
}
@Override
public void run() {
task.run();
}
@Override
public int compareTo(PriorityRunnable other) {
return Integer.compare(other.priority, this.priority);
}
}
PriorityBlockingQueue
实例,并将其传递给 ThreadPoolExecutor
:import java.util.concurrent.*;
public class PriorityScheduler {
public static void main(String[] args) {
int corePoolSize = 4;
PriorityBlockingQueue<Runnable> queue = new PriorityBlockingQueue<>();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, corePoolSize, 0L, TimeUnit.MILLISECONDS, queue);
// 提交任务
executor.submit(new PriorityRunnable(1, () -> System.out.println("Task with priority 1")));
executor.submit(new PriorityRunnable(3, () -> System.out.println("Task with priority 3")));
executor.submit(new PriorityRunnable(2, () -> System.out.println("Task with priority 2")));
executor.shutdown();
}
}
在这个示例中,我们创建了一个具有 4 个核心线程的线程池。当提交新任务时,它们将根据优先级顺序执行。请注意,这种方法可能会导致线程饥饿,因为高优先级任务可能会持续占用线程,从而阻止低优先级任务的执行。为了避免这种情况,可以考虑使用更复杂的调度策略,例如基于时间片轮转的调度。