是否可以在Stream.parallel()中设置线程的优先级?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了是否可以在Stream.parallel()中设置线程的优先级?相关的知识,希望对你有一定的参考价值。
如果我想在后台任务中并行运行Stream,是否可以以较低优先级运行它?如果是这样怎么样?
答案
对的,这是可能的。
程序如下:
- 创建一个
ForkJoinWorkerThreadFactory
,创建具有适当优先级的线程。 - 使用上面的线程工厂创建一个
ForkJoinPool
。 - 实例化并行流。
- 通过将流提交到
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)
另一答案
我认为更好的方法就像描述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);
以上是关于是否可以在Stream.parallel()中设置线程的优先级?的主要内容,如果未能解决你的问题,请参考以下文章