我有一台服务器,它不断监听客户端连接,并在每次客户端连接以处理该客户端的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 - 适用于多线程服务器的Java CachedThreadPool与FixedThreadPool,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54105478/