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

时间:2017-11-26 03:44:05

标签: java java-8 java-stream java-threads

如果我想在后台任务中并行运行Stream,是否可以以较低优先级运行它?如果是这样的话?

2 个答案:

答案 0 :(得分:9)

是的,这是可能的。

程序如下:

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

  2. 使用上述线程工厂创建ForkJoinPool

  3. 实例化并行流。

  4. 通过将流提交到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();

  5. 来运行该流

    这样的事情:

    {{1}}

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

答案 1 :(得分:0)

我认为一种更好的方法类似于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;
    }
}

它允许您仍然使用“默认” ForkJoinWorkerThread,但可以设置优先级/名称/等。使用如下方法:

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