在 Java 中指定任务顺序执行

我搜索了很多,但找不到任何解决方案。我以这种方式使用java线程池:

ExecutorService c = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; ++i) {
  c.execute(new MyTask(i));
}

通过这种方式,任务按后续顺序执行(如在队列中)。但我需要改变“选择下一个任务”的策略。因此,我想为每个任务分配指定优先级(它不是线程优先级),并执行与这些优先级相对应的任务。因此,当执行器完成另一个任务时,它会选择下一个任务作为具有最大优先级的任务。它描述了常见问题。也许有更简单的方法不考虑优先级。它选择上次添加的任务作为下一个要执行的任务,而不是首先添加。粗略地说,FixedThreadPool使用FIFO策略。例如,我可以使用后进先出策略吗?


答案 1

可以使用 PriorityBlockingQueue 指定 Queue to ThreadPoolExecutor。

public class PriorityExecutor extends ThreadPoolExecutor {

    public PriorityExecutor(int corePoolSize, int maximumPoolSize,
            long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }
    //Utitlity method to create thread pool easily
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new PriorityExecutor(nThreads, nThreads, 0L,
                TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>());
    }
    //Submit with New comparable task 
    public Future<?> submit(Runnable task, int priority) {
        return super.submit(new ComparableFutureTask(task, null, priority));
    }
    //execute with New comparable task 
    public void execute(Runnable command, int priority) {
        super.execute(new ComparableFutureTask(command, null, priority));
    }
}

定义以比较优先级。ComparableFutureTask

class ComparableFutureTask<T> extends FutureTask<T>
        implements
            Comparable<ComparableFutureTask<T>> {

    volatile int priority = 0;

    public ComparableFutureTask(Runnable runnable, T result, int priority) {
        super(runnable, result);
        this.priority = priority;
    }
    public ComparableFutureTask(Callable<T> callable, int priority) {
        super(callable);
        this.priority = priority;
    }
    @Override
    public int compareTo(ComparableFutureTask<T> o) {
        return Integer.valueOf(priority).compareTo(o.priority);
    }
  }

答案 2

ThreadPoolExecutor 构造函数接受 BlockingQueue。您可以将队列作为优先级阻止队列传递。它不会使任何受让人在订购时需要通过自定义比较器来维持订单。

static BlockingQueue<Task> queue=new PriorityBlockingQueue<Task>(MAXPOOL,new TaskComparator());

static ThreadPoolExecutor threadpool = new ThreadPoolExecutor(30, MAXPOOL, 
        MAXPOOL, TimeUnit.SECONDS, (PriorityBlockingQueue) queue, new mThreadFactory());



class TaskComparator implements Comparator<Task>{
  public int compare(Task t1, Task t2){
    //write you own logic to compare two task.
  }
}