用于多线程服务器的 Java CachedThreadPool 与 FixedThreadPool

标签 java multithreading executorservice

我有一个服务器,它不断监听客户端连接,并在每次客户端连接时创建一个新线程来处理该客户端的 I/O。现在,我有多个实现 Runnable 的类,并且在 run 方法中有一个 while 循环,该循环一直持续到客户端关闭。我创建了一个新的 Thread 对象并将可运行对象传递给该对象。我很确定还有其他更有效的方法可以做到这一点。我应该切换到 cachedThreadPool 或 fixedThreadPool 还是其他?

最佳答案

我建议使用 Executors#cachedThreadPool如果未定义客户的大小。

文档 Executors#cachedThreadPool :

* 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 {@code 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.

文档 Executors#fixedThreadPool :

* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue.  At any point, at most
* {@code 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.

因此,如果您不确定是否确实需要 5 个线程,则不应使用 Executors#fixedThreadPool .

关于用于多线程服务器的 Java CachedThreadPool 与 FixedThreadPool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54105478/

相关文章:

java - Spring 3 通过注释进行任务调度在服务器上同时运行多个实例

python - 在某些情况下,Python 线程可以安全地操作共享状态吗?

java - Java Future 重复超时导致 JVM 内存不足

java - C++ 代码中的 JNI 全局静态变量

java - 编译 Java 类并从命令控制台运行 Java 文件时,如何包含 Java jar 文件?

Java Web 开发 : Class transfer is too mechanical, 有替代方案吗?

java - 推荐 XML Difference 开源 Java 库吗?

c# - 如何等待一个方法在另一个线程上完成?

java - 如何在返回 Futures 的 Java ExecutorService 中调试 Callable

java - 执行者取消未决任务 - 需要帮助