1.线程池类为 java.util.concurrent.ThreadPoolExecutor,
常用构造方法为:
ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime, TimeUnit unit,BlockingQueue<Runnable> workQueue,RejectedExecutionHandler handler)
2.使用线程池的好处:
-
降低资源消耗:通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
-
提高响应速度:当任务到达时,可以不需要等待线程创建就能立即执行。
-
提高线程的可管理性:线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,监控和调优。
3.线程池的核心参数如下:
4.线程池的参数说明:
5.线程池原理分析:
6.基本使用:
/**
* Created by Administrator on 2020/5/17 0017.
*/
public class ThreadPoolExecutorTest {
public static void main(String[] args){
ThreadPoolExecutor executor = new ThreadPoolExecutor(2,10,10L, TimeUnit.SECONDS,new LinkedBlockingQueue(20));
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("hello,execute");
}
});
Future<String> future = executor.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("hello,future");
return "Success";
}
});
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
7.运行结果如下: