简体   繁体   English

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

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

If I want to run a Stream in parallel in a background task is it possible to run it in lower priority? 如果我想在后台任务中并行运行Stream,是否可以以较低优先级运行它? And if so how? 如果是这样怎么样?

Yes it is possible. 对的,这是可能的。

The procedure is as follows: 程序如下:

  1. Create a ForkJoinWorkerThreadFactory that creates threads with an appropriate priority. 创建一个ForkJoinWorkerThreadFactory ,用于创建具有适当优先级的线程。

  2. Create a ForkJoinPool using the above thread factory. 使用上面的线程工厂创建一个ForkJoinPool

  3. Instantiate the parallel stream. 实例化并行流。

  4. Run the stream by submitting it to the ForkJoinPool 通过将流提交到ForkJoinPool来运行流

Something like this: 像这样的东西:

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();

(Example code adapted from http://www.baeldung.com/java-8-parallel-streams-custom-threadpool ) (示例代码改编http://www.baeldung.com/java-8-parallel-streams-custom-threadpool

I think a better way to do this is like described here : 我认为更好的方法就像这里描述的那样:

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;
    }
}

It allows you to still use a "default" ForkJoinWorkerThread, but you can set priority / name / etc. Use like this: 它允许你仍然使用“默认”ForkJoinWorkerThread,但你可以设置优先级/名称/等。使用如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM