在Java中,ThreadPoolExecutor
本身并不支持任務優先級。但是,你可以通過以下方法實現任務優先級:
PriorityBlockingQueue
作為工作隊列:PriorityBlockingQueue
是一個支持優先級的阻塞隊列,它可以根據任務的優先級對任務進行排序。你可以創建一個自定義的任務類(實現 Runnable
或 Callable
接口),并在其中定義一個優先級屬性。然后,將任務類作為參數傳遞給 PriorityBlockingQueue
的構造函數。class PriorityTask<T extends Comparable<T>> implements Runnable, Comparable<PriorityTask<T>> {
private T priority;
private Runnable task;
public PriorityTask(T priority, Runnable task) {
this.priority = priority;
this.task = task;
}
@Override
public void run() {
task.run();
}
@Override
public int compareTo(PriorityTask<T> other) {
return other.priority.compareTo(this.priority);
}
}
ThreadPoolExecutor
:繼承 ThreadPoolExecutor
類,并重寫 newTaskFor
方法。在這個方法中,將任務包裝成一個 PriorityTask
對象,并將其提交給 PriorityBlockingQueue
。class PriorityThreadPoolExecutor extends ThreadPoolExecutor {
public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
if (callable instanceof PriorityCallable) {
return new PriorityFutureTask<>((PriorityCallable<T>) callable);
} else {
throw new IllegalArgumentException("Callable must implement PriorityCallable");
}
}
}
PriorityCallable
接口,該接口擴展了 Callable
接口并添加了一個 getPriority()
方法。class PriorityFutureTask<T> extends FutureTask<T> implements Comparable<PriorityFutureTask<T>> {
private final int priority;
public PriorityFutureTask(Callable<T> callable) {
super(callable);
if (!(callable instanceof PriorityCallable)) {
throw new IllegalArgumentException("Callable must implement PriorityCallable");
}
this.priority = ((PriorityCallable<T>) callable).getPriority();
}
@Override
public int compareTo(PriorityFutureTask<T> other) {
return Integer.compare(other.priority, this.priority);
}
}
PriorityThreadPoolExecutor
提交任務:PriorityThreadPoolExecutor executor = new PriorityThreadPoolExecutor(3, 5, 60, TimeUnit.SECONDS, new PriorityBlockingQueue<>());
executor.submit(new PriorityTask<>(1, () -> {
System.out.println("Task with priority 1 is running");
return null;
}));
executor.submit(new PriorityTask<>(3, () -> {
System.out.println("Task with priority 3 is running");
return null;
}));
executor.shutdown();
這樣,PriorityThreadPoolExecutor
將根據任務的優先級對任務進行排序,優先級較高的任務將優先執行。