ForkJoinPool.commonPool()有什么要注意的吗?
时间: 2023-12-19 11:01:55 浏览: 37
ForkJoinPool.commonPool() 是Java 8中引入的一个线程池,它是一个静态公共池,用于支持ForkJoinTask实现。调用该方法返回的是一个ForkJoinPool对象,该对象默认创建的线程数是当前计算机的处理器个数,可以通过设置系统属性 "java.util.concurrent.ForkJoinPool.common.parallelism" 来改变线程数。使用 ForkJoinPool.commonPool() 时需要注意以下几点:
1. ForkJoinPool.commonPool() 是一个静态公共池,因此它会被所有的ForkJoinTask共享,如果某个ForkJoinTask的执行时间过长,将会阻塞其他任务的执行。
2. ForkJoinPool.commonPool() 的线程数是默认的,如果需要更精细的控制线程数,可以通过创建自定义的ForkJoinPool对象来实现。
3. ForkJoinPool.commonPool() 执行的任务应该是CPU密集型的任务,如果执行的是I/O密集型的任务,可能会导致线程池中的线程阻塞,从而影响系统的性能。
4. ForkJoinPool.commonPool() 的线程数是与处理器相关的,如果处理器的个数发生变化,线程数也会相应地发生变化。因此,在使用 ForkJoinPool.commonPool() 时,应该考虑到处理器数量的变化。
相关问题
ForkJoinPool.commonPool() 线程池大小
ForkJoinPool.commonPool() 是 Java 中的一个默认线程池实例,它是基于Fork-Join框架实现的。它的大小是根据当前系统的CPU核心数来动态调整的。
在 Java 8 中,默认情况下,ForkJoinPool.commonPool() 的大小是根据 Runtime.getRuntime().availableProcessors() 方法返回的 CPU 核心数来决定的。它的最大线程数默认为 CPU 核心数减一。
但是需要注意的是,如果你调整了 ForkJoinPool.common.parallelism 系统属性,那么它的大小就不再是默认值,而是根据你设置的值来决定。你可以通过 System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "N") 来设置线程池的大小为 N。
总结来说,ForkJoinPool.commonPool() 的线程池大小取决于系统的 CPU 核心数,并且可以通过系统属性进行调整。
ForkJoinPool.commonPool()线程池的默认参数是什么
根据引用[2]中的介绍,ForkJoinPool.commonPool()线程池的默认参数如下:
- 并行级别:默认为当前CPU的核心数,可以通过`Runtime.getRuntime().availableProcessors()`获取。
- 工作线程数量:默认为当前CPU的核心数,可以通过`java.util.concurrent.ForkJoinPool.common.parallelism`系统属性进行设置。
- 工作窃取算法:默认为LIFO(后进先出)。
代码示例:
```java
int parallelism = Runtime.getRuntime().availableProcessors();
int commonParallelism = ForkJoinPool.getCommonPoolParallelism();
System.out.println("默认并行级别:" + parallelism);
System.out.println("默认工作线程数量:" + commonParallelism);
System.out.println("默认工作窃取算法:LIFO");
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)