- 并发编程中,线程池是很重要的一块内容。
线程池是一种池化技术,线程池、字符串常量池和数据库链接池都属于池化技术。
使用线程池的好处:
1.提高了线程的利用率(想一想,我们不可能每打一个电话,就去买一部手机吧?),节省新启一个线程和销毁一个线程需要的资源消耗。
2.提高了程序的响应速度
3.方便统一管理线程对象
4.可以控制最大的并发数
线程池的模型如下:
其实和在银行办理业务是一样的
对应关系如下:
顾客–》任务
线程池–》银行
线程池中的线程对象–》银行的服务窗口
队列–》座位
在java中我们在使用线程池的时候,
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(3,
5,
1L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(3)
, Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
对应API
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime