线程池的简单了解
类ThreadPoolExecutor继承AbstractExecutorService抽象类,而AbstractExecutorService抽象类实现接口ExecutorService,而接口ExecutorService继承接口Executor。下面就来讲讲ThreadPoolExecutor的用法
ThreadPoolExecutor的六个参数
int corePoolSize 核心线程数,即确定有多少个核心线程。
int maximumPoolSize 最大线程数,即限定线程池中的最大线程数量。
long keepAliveTime 非核心线程的存活时间,配合下面的TimeUnit参数确定时间。
TimeUnit unit 保持活跃时间的单位。可选为:NANOSECONDS,MICROSECONDS,MILLISECONDS,SECONDS,MINUTES,HOURS,DAYS等
BlockingQueue workQueue 工作队列。这队列用来保持那些execute()方法提交的还没有执行的任务。常用的队列有SynchronousQueue,LinkedBlockingQueue,ArrayBlockingQueue。一般我们需要根据自己的实际业务需求选择合适的工作队列。
ThreadFactory threadFactory 线程工厂,这是一个函数式接口,里面只定义了一个newThread(Runnable task)方法,需要自己实现工厂的方法,在这里我们可以对线程进行自定义的初始化,例如给线程设定名字,这样方便后期的调试。
RejectedExecutionHandler handler 拒绝服务处理,这也是一个函数式接口,我们需要实现rejectedExecution(Runnable r, ThreadPoolExecutor executor)这个方法,这里可以根据需求自定义你希望在处理逻辑。当然Java里面也有已经定义好的四种策略静态类。可以通过ThreadPoolExecutor调用
代码案例
public class ThreadPoolExecutorExample {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 60,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));
threadPool.execute(new MyTask());
threadPool.execute(new MyTask());
System.out.println("核心线程数" + threadPool.getCorePoolSize());
System.out.println("最大线程数" + threadPool.getMaximumPoolSize());
System.out.println("线程池数" + threadPool.getPoolSize());
System.out.println("队列任务数" + threadPool.getQueue().size());
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
threadPool.shutdown();
}
}
class MyTask implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"hello");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果
核心线程数5
最大线程数10
线程池数2
pool-1-thread-1hello
队列任务数0
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
pool-1-thread-2hello