代码之家  ›  专栏  ›  技术社区  ›  Stephane Grenier

可以设置流中线程的优先级吗。并行()?

  •  10
  • Stephane Grenier  · 技术社区  · 7 年前

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

    2 回复  |  直到 7 年前
        1
  •  8
  •   srborlongan    7 年前

    是的,这是可能的。

    程序如下:

    1. 创建 ForkJoinWorkerThreadFactory 这将创建具有适当优先级的线程。

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

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

        2
  •  1
  •   Katharsas    7 年前

    我认为更好的方法是 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);