43

Executor によって実行されるタスクに優先順位を設定する可能性はありますか? JCIPでそれが可能であるという声明をいくつか見つけましたが、例が見つからず、ドキュメントに関連するものも見つかりません。

JCIP より:

実行ポリシーは、次のようなタスク実行の「何を、どこで、いつ、どのように」を指定します。

  • ...
  • タスクはどのような順序で実行する必要がありますか (FIFO、LIFO、優先順位)?
  • ...

UPD : 聞きたいことを正確に聞いていないことに気付きました。私が本当に欲しかったのは:

エグゼキューターフレームワークでスレッドの優先順位の設定を使用/エミュレートする方法(つまり、何だったのかthread.setPriority())?

4

8 に答える 8

71

現在、 Executor インターフェースの具体的な実装は、ThreadPoolExecutorScheduledThreadpoolExecutorのみです。

ユーティリティ/ファクトリ クラスのExecutorsを使用する代わりに、コンストラクタを使用してインスタンスを作成する必要があります。

BlockingQueueを ThreadPoolExecutor のコンストラクターに渡すことができます。

BlockingQueue の実装の 1 つであるPriorityBlockingQueueを使用すると、Comparator をコンストラクターに渡して、実行順序を決定できます。

于 2010-07-07T21:24:26.220 に答える
45

ここでの考え方は、executor で PriorityBlockingQueue を使用することです。このため:

  • 先物を比較するコンパレータを作成します。
  • Future が優先順位を保持するためのプロキシを作成します。
  • プロキシですべての未来をラップするために、「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
于 2013-05-16T01:23:33.693 に答える
4

独自の ThreadFactory を実装し、次のように ThreadPoolExecutor 内に設定できます。

ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, numOfWorkerThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
threadPool.setThreadFactory(new OpJobThreadFactory(Thread.NORM_PRIORITY-2));

私の OpJobThreadFactory は次のようになります。

public final static class OpJobThreadFactory implements ThreadFactory {
   private int priority;
   private boolean daemon;
   private final String namePrefix;
   private static final AtomicInteger poolNumber = new AtomicInteger(1);
   private final AtomicInteger threadNumber = new AtomicInteger(1);

   public OpJobThreadFactory(int priority) {
      this(priority, true);
   }

   public OpJobThreadFactory(int priority, boolean daemon) {
      this.priority = priority;
      this.daemon = daemon;
      namePrefix = "jobpool-" +poolNumber.getAndIncrement() + "-thread-";
   }

   @Override
   public Thread newThread(Runnable r) {
      Thread t = new Thread(r, namePrefix + threadNumber.getAndIncrement());
      t.setDaemon(daemon);
      t.setPriority(priority);
      return t;
   }
}
于 2013-09-18T10:08:57.893 に答える
3

ThreadPoolExecutor を優先ブロッキング キューで使用できます ThreadPoolExecutor とカスタム タスクで PriorityBlockingQueue を実装する方法

于 2011-04-22T11:38:26.967 に答える
2

コンストラクタ(またはファクトリメソッド)で aThreadFactoryを指定できます。これにより、エグゼキュータに特定のスレッド優先度のスレッドを提供できます。ThreadPoolExecutorExecutors

ジョブごとに異なるスレッド優先度を取得するには、それらを異なるスレッド ファクトリを持つエグゼキュータに送信する必要があります。

于 2013-01-11T21:46:08.337 に答える
1

setPriority(..)は通常Linuxでは機能しないことに注意してください。詳細については、次のリンクを参照してください。

于 2012-06-25T06:55:58.610 に答える