gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:42 25 4
gpt4 key购买 nike

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

最佳答案

是的,这是可能的。

过程如下:

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

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

  3. 实例化并行流。

  4. 通过将流提交到 ForkJoinPool

  5. 来运行流

像这样:

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)

关于java - 是否可以在 Stream.parallel() 中设置线程的优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47492819/

25 4 0