线程池原理分析以及常见的创建方式
线程池在代码中用的还是比较多,不管什么,都是用的池子,比如JDBC。在做一个生活中的例子吧,比如说你洗菜肯定会给要洗的才放入洗菜盆中来洗(洗菜盆就相当于一个池子),你肯定不会一根一根的洗,浪费水资源不说,最主要的还浪费水资源。
请原谅我是一个平顶山人,我对象都说我很啰嗦,但是我也没有感觉。
a).什么是线程池以及它的作用
b).JAVA开发中,合理的使用线程池有三大好处;
c).线程池的分类
e).线程池的原理分析
f).合理的配置线程数数量
------------------------------------------------------华丽的分界线------------------------------------------------------
a).什么是线程池以及它的作用
JAVA中线程池是运用最多的并发框架,几乎所有并发或者异步的编程都可以使用线程池。
主要就是通过几个固定的线程来操作服务,减少了创建和销毁线程的过程,从而提高效率。
b).JAVA开发中,合理的使用线程池有三大好处;
a).降低消耗资源
通过重复的创建线程以及销毁线程能够降低消耗
b).提高响应速度
当 达到任务时候,任务可以不等到线程创建就能执行任务
c).提高线程的可管理性
线程比较稀缺,如果过度的创建线程,不仅不能够优化代码,而且还会降低系统的性能。可以使用I线程池统一分配,管理,监控。
c).线程池的分类
前言:JAVA支持并发,但是频繁的创建线程和销毁线程会很浪费资源的,并且线程又很宝贵的。在JDK1.5以前的版本中,线程池非常的丑陋的,但是在JDK1.5之后加入了java.uril.concurrent包,对并发有了一个很大的帮助。今天主要说下Executor接口。
d).线程池创建的四种方式
前言:Executor框架最顶层的是ThreadPoolExecutor类,Executors主要提供的有newScheduledThreadPool,newFixedThreadPool,newCachedThreadPool,newSingleThreadExcutor,只是构造方法,参数不同,可以适用不同的场景
第一种:newCachedThreadPool:
创建一个可缓存的线程池,缓存线程池如果超过处理需要,可回收线程。比如说:线程池虽然创建了10个线程,但是运行的线程只有4个,线程用完之后回收,方便其他线程来使用
package com.aaa.demoThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewCachedThreadPoolDemo {
public static void main(String[] args) {
//创建的是newCachedThreadPool线程池子
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for(int i=0;i<30;i++){
int temp=i;
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("名称:"+Thread.currentThread().getName()+"执行的是:"+temp);
}
});
}
}
}
结果如图:
第二种:newFixedThreadPool:
创建一个定长线程池,可控制最大并发数,超出的线程数量会在外边等待
package com.aaa.demoThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class NewFixedThreadPool {
public static void main(String[] args) {
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 20; i++) {
int temp=i;
newFixedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"i:"+temp);
}
});
}
}
}
结果如图所示;
第三种:newScheduledThreadPool:
这个线程池会定时调用方法
package com.aaa.demoThread;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class NewScheduledThreadPool {
public static void main(String[] args) {
ScheduledExecutorService newScheduledThreadPool = Executors.newScheduledThreadPool(3);
for (int i = 0; i < 10; i++) {
int temp= i;
newScheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println("名称:"+Thread.currentThread().getName()+"执行的是:"+temp);
}
}, 5, TimeUnit.SECONDS);
}
}
}
5s运行结果:
第三种:newSingleThreadPool:
这个是一个单例的线程,实战中几乎用到的不多
package com.aaa.demoThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class newSingleThreadPool {
public static void main(String[] args) {
ExecutorService newSingleThreadExecutor = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int index = i;
newSingleThreadExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("index:" + index);
try {
Thread.sleep(200);
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
}
}
如图所示:
e).线程池的原理分析
看源码:这里拿newFixedThreadPool举栗子,点击newFixedThreadPool的execute进入ThreadPoolExcutor
/**
* Executes the given task sometime in the future. The task
* may execute in a new thread or in an existing pooled thread.
*
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
* {@code RejectedExecutionHandler}, if the task
* cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
核心:
最主要的区别就是核心线程数和最大线程数量:
a).用户线程>核心线程数 -----> 将大于核心线程的数量放在队列线程中 -----> 继续执行任务 --------> 用户线程>缓存队列线程 ---------> 将大于最大线程数量 ------> 放在最大线程池里边 -----> 用户线程>最大线程 -------> 出现异常
自己来一个画图:
多线程总结:
四种线程池都是基于ThreadPoolExecutor,但是是根据不同的构造方法来搞的,主要是四个参数,根据不同的构造方法来完成不同的需求。
参数说明:
CorePoolSize:核心线程池的大小。当任务来了之后就会执行任务,如果当前线程达到了CorePoolSize十周,就会给线程放在缓存池中。。
MaxnumPoolSize:线程池的最大数量。表示的是线程池中最多创建的线程池数量。
keepAliveTime:表示的当前线程池没有变成线程执行时,保持多久时间会终止。
unit:表示的是keepAliveTime的时间单位。主要有年月日,时分秒
f).合理的配置线程数数量
主要从两个方面来考虑线程数量
a)CPU密集 b).I/O密集
https://blog.****.net/wt520it/article/details/87894309
CPU密集型时,任务可以少配置线程数,大概和机器的cpu核数相当,这样可以使得每个线程都在执行任务
IO密集型时,大部分线程都阻塞,故需要多配置线程数,2*cpu核数
操作系统之名称解释:
某些进程花费了绝大多数时间在计算上,而其他则在等待I/O上花费了大多是时间,
前者称为计算密集型(CPU密集型)computer-bound,后者称为I/O密集型,I/O-bound。
在实战中学习,在快乐中成长