Forcing multiple threads to use multiple CPUs when they are available

后端 未结 10 1169
后悔当初
后悔当初 2020-11-28 19:21

I\'m writing a Java program which uses a lot of CPU because of the nature of what it does. However, lots of it can run in parallel, and I have made my program multi-threade

10条回答
  •  广开言路
    2020-11-28 19:56

    You can use below API from Executors with Java 8 version

    public static ExecutorService newWorkStealingPool()
    

    Creates a work-stealing thread pool using all available processors as its target parallelism level.

    Due to work stealing mechanism, idle threads steal tasks from task queue of busy threads and overall throughput will increase.

    From grepcode, implementation of newWorkStealingPool is as follows

    /**
         * Creates a work-stealing thread pool using all
         * {@link Runtime#availableProcessors available processors}
         * as its target parallelism level.
         * @return the newly created thread pool
         * @see #newWorkStealingPool(int)
         * @since 1.8
         */
        public static ExecutorService newWorkStealingPool() {
            return new ForkJoinPool
                (Runtime.getRuntime().availableProcessors(),
                 ForkJoinPool.defaultForkJoinWorkerThreadFactory,
                 null, true);
        }
    

提交回复
热议问题