线程池

基本思想(对象池的思想)

内存中开辟一块空间,里面存放众多未死亡的对象,线程的调度由线程池管理,当有线程任务时,从池中取出一个,使用完毕再归还给线程池,这样避免了反复创建线程对象所带来的性能开销,节省了系统资源。

分类

  1. cacheTheadPool (可变数量的线程池,缓存线程池)
  • 缓存类型的池子,先看池子中之前创建的线程,有的话复用,没有则重新创建
  • 能复用的线程,必须是timeout idle pool中的线程,默认的timeout为60s,超时的线程会被移出线程池
  • 适用于一些生存周期短的异步型任务,面向连接的daemon类型的server中用的不多
  1. FixThreadPool (固定数量的线程池)
  • 复用原则同cacheThreadPool相同
  • 在任意时间段内,只允许固定的线程存在于线程池,超出则在等待队列中等待,直至池中有线程死亡被移除
  • 底层使用无idle机制,或超时时间很长,所以多适用于服务器,很稳定并固定的正规并发编程
  • 底层使用的是一个池子,只是参数同cacheTheadPool不同,fix支持固定数量的线程池,0s无超时(idle),cache是支持0-Integer.max_value大小的线程池,完全没有考虑到主机资源承受压力问题,60sidle。
/**
 * 固定数量的线程池
 * @author 98543
 */
public class FixPool {
	public static void main(String[] args) {
		// 创建一个可重复使用的线程池
		ExecutorService executor = Executors.newFixedThreadPool(5);
		FixPool pool = new FixPool();
		Thread t1 = pool.new Runner();
		Thread t2 = pool.new Runner();
		Thread t3 = pool.new Runner();
		Thread t4 = pool.new Runner();
		Thread t5 = pool.new Runner();
		// 线程放入线程池
		executor.execute(t1);
		executor.execute(t2);
		executor.execute(t3);
		executor.execute(t4);
		executor.execute(t5);
		// 关闭线程池
		executor.shutdown();
	}
	
	
	class Runner extends Thread{
		public void run() {
			System.out.println(Thread.currentThread().getName()+"正在执行");
			try {
				TimeUnit.SECONDS.sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
  1. ScheduledThreadPool
  • 任务调度类型的线程池
  1. SingleThreadExecutor
  • 底层和fix使用同一个池子,但数量是1-1
  1. 自定义线程池
ThreadPoolExecutor executor2 = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
  • corePoolSize:核心线程数
  • maximumPoolSize:池中最大线程数
  • keepAliveTime:线程超时时间
  • workQueue:执行前用于保持任务的队列
    使用示例:
// 创建等待队列
		BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(5);
		ThreadPoolExecutor executor2 = new ThreadPoolExecutor(5, 6, 30, TimeUnit.SECONDS, queue);

参考链接

posted @ 2019-10-21 09:47  kungFuPander  阅读(117)  评论(0编辑  收藏  举报