Java线程池适用范围

来源:互联网 发布:网络电视在线直播 编辑:程序博客网 时间:2024/05/17 04:57


查自API文档:

ExecutorService threadPool = Executors.newFixedThreadPool(3);// 创建可以容纳3个线程的线程池  

newFixedThreadPool:

  • Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at mostnThreads 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 explicitlyshutdown.

newCachedThreadPool:

  • 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 toexecute 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 usingThreadPoolExecutor constructors.

newSingleThreadExecutor:

  • Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalentnewFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
newScheduledThreadPool:

  • Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.