是否可以在Stream.parallel() 中设置线程的优先级?

Is it possible to set the priority of the threads in Stream.parallel()?

如果我想 运行 在后台任务中并行处理一个流,是否可以 运行 它的优先级较低?如果是的话怎么办?

是的,这是可能的。

程序如下:

  1. 创建一个 ForkJoinWorkerThreadFactory 以创建具有适当优先级的线程。

  2. 使用上面的线程工厂创建一个ForkJoinPool

  3. 实例化并行流。

  4. 运行 将流提交到 ForkJoinPool

像这样:

public class MyThread extends ForkJoinWorkerThread {
    public MyThread(ForkJoinPool pool, int priority) {
        super(pool);
        setPriority(priority);
    }
}

final int poolSize = ...
final int priority = ...

List<Long> aList = LongStream.rangeClosed(firstNum, lastNum).boxed()
  .collect(Collectors.toList());

ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory() {
    public ForkJoinWorkerThread newThread(ForkJoinPool pool) {
         return new MyThread(pool, priority);
    }
};
/*
ForkJoinWorkerThreadFactory factory = pool -> new MyThread(
  pool,
  priority
);
*/

ForkJoinPool customThreadPool = new ForkJoinPool(
    poolSize, factory, null, false);
long actualTotal = customThreadPool.submit(
    () -> aList.parallelStream().reduce(0L, Long::sum)).get();

(示例代码 改编自 http://www.baeldung.com/java-8-parallel-streams-custom-threadpool

我认为更好的方法是描述 :

public class CustomForkJoinWorkerThreadFactory implements ForkJoinWorkerThreadFactory {

    private final int threadPriority;

    public CustomForkJoinWorkerThreadFactory(int threadPriority) {
        this.threadPriority = threadPriority;
    }

    @Override           
    public ForkJoinWorkerThread newThread(ForkJoinPool pool)
    {
        final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
        worker.setPriority(threadPriority);
        return worker;
    }
}

它允许你仍然使用一个"default" ForkJoinWorkerThread,但是你可以设置优先级/名称/等等。像这样使用:

new ForkJoinPool(poolSize, new CustomForkJoinWorkerThreadFactory(Thread.MIN_PRIORITY), null, false);