代码示例:
newFixedThreadPool: 一池五个线程
public static void main(String[] args){
//一池五个线程处理
ExecutorService threadPool=Executors.newFixedThreadPool(5);
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果 thread最多到5
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-2 办理业务
pool-1-thread-2 办理业务
pool-1-thread-2 办理业务
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-5 办理业务
pool-1-thread-4 办理业务
pool-1-thread-3 办理业务
newSingleThreadExecutor:多少请求都只有一个线程处理:
public static void main(String[] args){
//一池一个线程
ExecutorService threadPool=Executors.newSingleThreadExecutor();
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果:
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
newCachedThreadPool:一池多个线程:
public static void main(String[] args){
//一池N个处理线程,如果说一个线程可以搞定就一个线程如果说忙不过来就多个线程
ExecutorService threadPool=Executors.newCachedThreadPool();
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果:
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-3 办理业务
pool-1-thread-4 办理业务
pool-1-thread-5 办理业务
pool-1-thread-6 办理业务
pool-1-thread-7 办理业务
pool-1-thread-8 办理业务
pool-1-thread-9 办理业务
pool-1-thread-10 办理业务
public static void main(String[] args){
//一池N个处理线程,如果说一个线程可以搞定就一个线程如果说忙不过来就多个线程
ExecutorService threadPool=Executors.newCachedThreadPool();
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
//睡眠一下,忙得过来的时候就一个线程处理
Thread.sleep(300);
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果:
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
线程池的底层原理:
//newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
//newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
//newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
三个线程方式都是调的ThreadPoolExecutor对参数的解释:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
}
1.corePoolSize:
1.1在创建了线程池后,当有请求任务来之后,就会安排池中的线程去执行请求任务,近似理解为 今日当值线程
1.2当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
2.maximumPoolSize
线程池能够容纳同时执行的最大线程数,此值必须大于等于1 .
3.keepAliveTime:
多余的空闲线程的存活时间。
当前线程池数量超过corePoolSize时,当空闲时间达到keepAliveTime值时,多余空闲线程会被销毁直到只剩下corePoolSize个线程为止.
4.TimeUnit unit
keepAliveTime的单位
5.workQueue(阻塞队列)
任务队列,被提交但尚未被执行的任务(银行里面的候客区)
6.threadFactory
表示生成线程池中工作线程的线程工厂,用于创建线程一般用默认的即可(创建线程的特性)。
7. handler
拒绝策略,表示当队列满了并且工作线程大于等于线程池的最大线程maximumPoolSize
总结:首先请求来了,corePoolSize数的线程开始处理,后面来的请求存到阻塞队列workQueue,当corePoolSize和workQueue都满了就扩容(请求支援,添加线程处理),扩容到了maximumPoolSize值(线程最大值) 如果还有请求就直接启用拒绝策略,如果业务量慢慢的下来,在keepAliveTime变量设置的时间到了后没有请求了,就把支援的线程除了corePoolSize外的线程都销毁掉.
什么是拒绝策略:
等待队列也已经排满了,再也塞不下新任务了同时线程池中的max线程也达到了,无法继续为新任务服务。这时候我们就需要拒绝策略机制合理的处理这个问题.
1.AbortPolicy(默认):直接抛出RejectedExecutionException异常阻止系统正常运行。
2.callerRunsPolicy:“调用者运行一种调节机制,该策略既不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,
3.DiscardoidestPolicy:抛弃队列中等待最久的任务,然后把当前任务加入队列中尝试再次提交当前任务。
4.DiscardPolicy:直接丢弃任务,不予任何处理也不抛出异常。如果允许任务丢失,这是最好的一种方案。
AbortPolicy拒绝策略示例:
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
try{
for (int i = 1; i <=9 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果:
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-2 办理业务
pool-1-thread-2 办理业务
pool-1-thread-2 办理业务
pool-1-thread-3 办理业务
pool-1-thread-4 办理业务
pool-1-thread-5 办理业务
java.util.concurrent.RejectedExecutionException: Task com.hy.controller.ResController$$Lambda$1/1792845110@4ec6a292 rejected from java.util.concurrent.ThreadPoolExecutor@1b40d5f0[Running, pool size = 5, active threads = 4, queued tasks = 0, completed tasks = 4]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at com.hy.controller.ResController.main(ResController.java:1017)
CallerRunsPolicy示例: 回退到调用者
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy());
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果:
main 办理业务
main 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-3 办理业务
pool-1-thread-4 办理业务
pool-1-thread-5 办理业务
DiscardOldestPolicy示例:
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardOldestPolicy());
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果
pool-1-thread-2 办理业务
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-2 办理业务
pool-1-thread-1 办理业务
pool-1-thread-3 办理业务
pool-1-thread-5 办理业务
pool-1-thread-4 办理业务
DiscardPolicy示例:
public static void main(String[] args) {
ExecutorService threadPool =new ThreadPoolExecutor(2,5,
11, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.DiscardPolicy());
try{
for (int i = 1; i <=10 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"\t办理业务");
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
//执行结果:
pool-1-thread-1 办理业务
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-1 办理业务
pool-1-thread-2 办理业务
pool-1-thread-4 办理业务
pool-1-thread-3 办理业务
pool-1-thread-5 办理业务