我想知道在这个特定场景中使用哪个 CachedThreadPool
或 FixedThreadPool
。
当用户登录到应用程序时,将获得大约 10 个地址的地址列表。我需要执行以下操作:
- 将地址转换为我正在为其调用 Google API 的纬度和经度
- 也借助 Google API 获取上述获取的经纬度与用户当前位置之间的距离
因此,我创建了一个类 GetDistance
,它实现了 Runnable
。在本类(class)中,我首先调用 Google API 并解析响应以获取相应的纬度和经度,然后调用和解析另一个 Google API 的结果以获取行驶距离。
private void getDistanceOfAllAddresses(List<Items> itemsList) {
ExecutorService exService = newCachedThreadPool(); //Executors.newFixedThreadPool(3);
for(int i =0; i<itemsList.size(); i++) {
exService.submit(new GetDistance(i,usersCurrentLocation));
}
exService.shutdown();
}
我试过 CachedThreadPool
和 FixedThreadPool
,所用时间几乎相同。我赞成 CachedThreadPool,因为它被推荐用于小型操作,但我有一些顾虑。让我们假设 CachedThreadPool
创建 10 个线程(最坏情况)来完成该过程(10 个项目),如果我的应用程序在低端设备上运行,这会成为问题吗?由于创建的线程数也会影响设备的 RAM。
我想知道您对此的想法和意见。哪个更好用?
最佳答案
使用 newCachedThreadPool
它更适合这种情况,因为您的任务很小并且受 I/O(网络)限制。这意味着您应该创建多于处理器内核数量的线程(通常是 1.5 到 2 倍)以获得最佳输出,但我猜 newCachedThreadPool
会自行管理。因此,与 newFixedThreadPool
相比,newCachedThreadPool
的开销会更少,并且对您的情况有所帮助。
如果您有 CPU 密集型任务,那么 newFixedThreadPool
可能是更好的选择。
更新
A list of addresses will be obtained about 10 addresses.
如果您始终只需要 10 个地址,那么没关系,请使用 newCachedThreadPool
。但是,如果您认为地址数量可以增加,则使用 newFixedThreadPool
,线程数量 <= 可用内核数量的 1.5 倍到 2 倍。
来自 Java 文档:
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.
关于java - CachedThreadPool 与 FixedThreadPool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35859609/