本文主要介绍了java 线程池框架的相关知识。具有很好的参考价值,下面跟着小编一起来看下吧
一、线程池结构图
二、示例
定义线程接口
public class mythread extends thread {
@override
publicvoid run() {
system.out.println(thread.currentthread().getname() + "正在执行");
}
}
1:newsinglethreadexecutor
executorservice pool = executors. newsinglethreadexecutor();
thread t1 = new mythread();
thread t2 = new mythread();
thread t3 = new mythread();
//将线程放入池中进行执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
//关闭线程池
pool.shutdown();
输入结果:
pool-1-thread-1正在执行
pool-1-thread-1正在执行
pool-1-thread-1正在执行
2:newfixedthreadpool
executorservice pool = executors.newfixedthreadpool(3);
thread t1 = new mythread();
thread t2 = new mythread();
thread t3 = new mythread();
thread t4 = new mythread();
thread t5 = new mythread();
//将线程放入池中进行执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.shutdown();
输入结果:
pool-1-thread-1正在执行
pool-1-thread-2正在执行
pool-1-thread-1正在执行
pool-1-thread-2正在执行
3 :newcachedthreadpool
executorservice pool = executors.newcachedthreadpool();
thread t1 = new mythread();
thread t2 = new mythread();
thread t3 = new mythread();
thread t4 = new mythread();
thread t5 = new mythread();
//将线程放入池中进行执行
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
//关闭线程池
pool.shutdown();
输入结果:
pool-1-thread-2正在执行
pool-1-thread-4正在执行
pool-1-thread-3正在执行
pool-1-thread-1正在执行
pool-1-thread-5正在执行
4 :scheduledthreadpoolexecutor
scheduledexecutorservice pool = executors.newscheduledthreadpool(2);
pool.scheduleatfixedrate(new runnable() {//每隔一段时间就触发异常
@override
public void run() {
//throw new runtimeexception();
system.out.println("================");
}
}, 1000, 2000, timeunit.milliseconds);
pool.scheduleatfixedrate(new runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的
@override
public void run() {
system.out.println("+++++++++++++++++");
}
}, 1000, 2000, timeunit.milliseconds);
输入结果:
================
+++++++++++++++++
+++++++++++++++++
+++++++++++++++++
三、线程池核心参数
corepoolsize : 池中核心的线程数
maximumpoolsize : 池中允许的最大线程数。
keepalivetime : 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。
unit : keepalivetime 参数的时间单位。
workqueue : 执行前用于保持任务的队列。此队列仅保持由 execute方法提交的 runnable任务。
threadfactory : 执行程序创建新线程时使用的工厂。
handler : 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。
threadpoolexecutor :executors类的底层实现。
3.1 任务排队机制
synchonousqueue: 同步队列,队列直接提交给线程执行而不保持它们,此时线程池通常是无界的
linkedblockingqueue: 无界对列,当线程池线程数达到最大数量时,新任务就会在队列中等待执行,可能会造成队列无限膨胀
arrayblockingqueue : 有界队列,有助于防止资源耗尽,一旦达到上限,可能会造成新任务丢失
注意:
newsinglethreadexecutor、newfixedthreadpool使用的是linkedblockingqueue
newcachedthreadpool 使用的是 synchonousqueue
newscheduledthreadpool使用的是 delayedworkqueue
3.2 线程执行流程
3.3 线程大小确定:
cpu密集型: 尽量少开线程,最佳线程数 ncpu+1
io密集型:多开线程,2ncpu
混合型:根据情况而定,可以拆分成io密集和cou密集
更多java 线程池框架。
