本文介绍了在Java中指定任务顺序执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've searched a lot but couldn't find any solution.I use java thread pool in such way:

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

以这种方式执行任务按顺序执行(如队列中)。但我需要改变选择下一个任务策略。所以我希望为每个任务分配指定优先级(它不是线程优先级),并且执行任务对应于这些优先级。因此,当执行程序完成另一个任务时,它会将下一个任务选为具有最高优先级的任务。
它描述了常见问题。也许有更简单的方法不考虑优先级。它选择最后添加的任务作为执行而不是第一次添加。粗略地讲,FixedThreadPool使用FIFO策略。我可以使用例如LIFO策略吗?

In such way Tasks are executed in consequent order (as in queue). But I need change "select next task" strategy. So I want assign to each task specify priority (it isn't thread priority) and execute tasks correspond to these priorities. So when executor have finished another task it chooses next task as task with maximum priority.It describes common problem. Maybe there is more simple approach which doesn't account priorities. It selects last added task as next to execute instead of first added. Roughly speaking FixedThreadPool use FIFO strategy. Can I use for example LIFO strategy?

推荐答案

你可以使用指定Queue到ThreadPoolExecutor。

You can use PriorityBlockingQueue to specify 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);
    }
  }

这篇关于在Java中指定任务顺序执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:53