Java执行器:如何设置任务优先级?

是否有可能为执行者执行的任务设置优先级?我在JCIP中找到了一些关于这是可能的语句,但我找不到任何例子,我也找不到任何相关的文档。

来自 JCIP:

执行策略指定任务执行的“内容、位置、时间和方式”,包括:

  • ...
  • 任务应按什么顺序执行(先进先出、后进先出、优先顺序)?
  • ...

UPD:我意识到我问的并不完全是我想问的。我真正想要的是:

如何使用/模拟使用执行器框架设置线程优先级(即是什么)?thread.setPriority()


答案 1

目前,Executor接口的唯一具体实现是ThreadPoolExecutorReschardThreadpoolExecutor。

不应使用实用程序/工厂类执行器,而应使用构造函数创建实例。

您可以将 BlockingQueue 传递给 ThreadPoolExecutor 的构造函数。

作为 BlockingQueue 的实现之一,PriorityBlockingQueue 允许您将比较器传递给构造函数,这样您就可以决定执行顺序。


答案 2

这里的想法是在执行器中使用PriorityBlockingQueue。为此:

  • 创建一个比较器来比较我们的未来。
  • 为未来创建一个代理以占据优先级。
  • 覆盖“newTaskFor”,以便将每个未来包装在我们的代理中。

首先,你需要优先考虑你的未来:

    class PriorityFuture<T> implements RunnableFuture<T> {

    private RunnableFuture<T> src;
    private int priority;

    public PriorityFuture(RunnableFuture<T> other, int priority) {
        this.src = other;
        this.priority = priority;
    }

    public int getPriority() {
        return priority;
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return src.cancel(mayInterruptIfRunning);
    }

    public boolean isCancelled() {
        return src.isCancelled();
    }

    public boolean isDone() {
        return src.isDone();
    }

    public T get() throws InterruptedException, ExecutionException {
        return src.get();
    }

    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        return src.get();
    }

    public void run() {
        src.run();
    }
}

接下来,您需要定义能够正确排序优先级期货的比较器:

class PriorityFutureComparator implements Comparator<Runnable> {
    public int compare(Runnable o1, Runnable o2) {
        if (o1 == null && o2 == null)
            return 0;
        else if (o1 == null)
            return -1;
        else if (o2 == null)
            return 1;
        else {
            int p1 = ((PriorityFuture<?>) o1).getPriority();
            int p2 = ((PriorityFuture<?>) o2).getPriority();

            return p1 > p2 ? 1 : (p1 == p2 ? 0 : -1);
        }
    }
}

接下来,让我们假设我们有一个像这样的冗长工作:

class LenthyJob implements Callable<Long> {
    private int priority;

    public LenthyJob(int priority) {
        this.priority = priority;
    }

    public Long call() throws Exception {
        System.out.println("Executing: " + priority);
        long num = 1000000;
        for (int i = 0; i < 1000000; i++) {
            num *= Math.random() * 1000;
            num /= Math.random() * 1000;
            if (num == 0)
                num = 1000000;
        }
        return num;
    }

    public int getPriority() {
        return priority;
    }
}

然后,为了优先执行这些作业,代码将如下所示:

public class TestPQ {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        int nThreads = 2;
        int qInitialSize = 10;

        ExecutorService exec = new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,
                new PriorityBlockingQueue<Runnable>(qInitialSize, new PriorityFutureComparator())) {

            protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
                RunnableFuture<T> newTaskFor = super.newTaskFor(callable);
                return new PriorityFuture<T>(newTaskFor, ((LenthyJob) callable).getPriority());
            }
        };

        for (int i = 0; i < 20; i++) {
            int priority = (int) (Math.random() * 100);
            System.out.println("Scheduling: " + priority);
            LenthyJob job = new LenthyJob(priority);
            exec.submit(job);
        }
    }
}

这是很多代码,但这几乎是实现这一目标的唯一方法。

在我的机器上,输出如下所示:

Scheduling: 39
Scheduling: 90
Scheduling: 88
Executing: 39
Scheduling: 75
Executing: 90
Scheduling: 15
Scheduling: 2
Scheduling: 5
Scheduling: 24
Scheduling: 82
Scheduling: 81
Scheduling: 3
Scheduling: 23
Scheduling: 7
Scheduling: 40
Scheduling: 77
Scheduling: 49
Scheduling: 34
Scheduling: 22
Scheduling: 97
Scheduling: 33
Executing: 2
Executing: 3
Executing: 5
Executing: 7
Executing: 15
Executing: 22
Executing: 23
Executing: 24
Executing: 33
Executing: 34
Executing: 40
Executing: 49
Executing: 75
Executing: 77
Executing: 81
Executing: 82
Executing: 88
Executing: 97

推荐