一、invokeAll
Executors支持通过invokeAll()
一次批量提交多个callable。这个方法结果一个callable的集合,然后返回一个future的列表。
1 public static void main(String[] args) throws InterruptedException { 2 // 根据cpu是几核来开启几个线程 3 ExecutorService service = Executors.newWorkStealingPool(); 4 List<Callable<String>> callables = Arrays.asList( 5 () -> "task1", 6 () -> "task2", 7 () -> "task3", 8 () -> "task4", 9 () -> "task5"); 10 11 service.invokeAll(callables) 12 .stream() 13 .map(future -> { 14 try { 15 return future.get(); 16 } 17 catch (Exception e) { 18 throw new IllegalStateException(e); 19 } 20 }) 21 .forEach(System.out::println); 22 }
看一下Executors.newWorkStealingPool()调用源码为:
1 /** 2 * Creates a work-stealing thread pool using all 3 * {@link Runtime#availableProcessors available processors} 4 * as its target parallelism level. 5 * @return the newly created thread pool 6 * @see #newWorkStealingPool(int) 7 * @since 1.8 8 */ 9 public static ExecutorService newWorkStealingPool() { 10 return new ForkJoinPool 11 (Runtime.getRuntime().availableProcessors(), 12 ForkJoinPool.defaultForkJoinWorkerThreadFactory, 13 null, true); 14 }
实际上Runtime.getRuntime().availableProcessors()获取CPU是集合,那么就开启几个线程来执行(通常默认为JVM可用的处理器个数)。
看到还有另外一个ForkJoinPool.defaultForkJoinWorkerThreadFactory,源码是这样的:
1 /** 2 * Default ForkJoinWorkerThreadFactory implementation; creates a 3 * new ForkJoinWorkerThread. 4 */ 5 static final class DefaultForkJoinWorkerThreadFactory 6 implements ForkJoinWorkerThreadFactory { 7 public final ForkJoinWorkerThread newThread(ForkJoinPool pool) { 8 return new ForkJoinWorkerThread(pool); 9 } 10 }
结合其他源码看起来ForkJoinPool:
1.初始化了一个线程池ForkJoinWorkerThread[parallelism..
2.初始化了一个任务队列submissionQueue[8]。
--->每天进步一点!!!<---