在多线程编程基础(一)中,讲到了线程最基本的使用方法。可是在阿里的开发规范上,这是不值得推荐的。能够在idea中下一个Alibaba Java Coding Guidelines
,来纠正咱们开发时的习惯。 java
就上面的第一个问题,咱们引入的是一个线程池的概念。想来以前在享元模式中,咱们就说起过缓冲池的概念,那么线程池是什么样的呢?编程
从图中咱们能够得到信息有设计模式
固然,其实须要的参数还有不少。多线程
// ThreadPoolExecutor的构造函数
ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
复制代码
线程池分为不少种类,最经常使用的是这四种:FixedThreadPool、CachedThreadPool、SingleThreadExecutor、ScheduledThreadPool。并发
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
复制代码
从填入的函数能够看出最大线程数和核心线程数的数量相同,也就意味着只有核心线程了,多出的任务,将会被放置到LinkedBlockingQueue
中。ide
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
复制代码
没有核心线程,最大线程数为无穷,也就意味着所有都是非核心线程。这样的线程池更适合去完成大量须要当即处理,可是耗时短的任务。函数
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
复制代码
核心线程数和最大线程数相同,且都为1,也就意味着任务是按序工做的。post
public static ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
复制代码
从函数名就已经说明了,是一种定时任务。其实就个人思考,他能够用于实现各类各样功能相似的其余线程池。由于DelayedWorkQueue
队列中你能够插入一个马上须要执行的任务。学习
每次使用线程咱们是否是须要去建立一个
Thread
,而后start()
,而后就等结果,最后的销毁就等着垃圾回收机制来了。 可是问题是若是有1000个任务呢,你要建立1000个Thread吗?若是建立了,那回收又要花多久的时间?ui
存在核心线程和非核心线程,还有任务队列,那么就能够保证资源的争夺是处于一个尽可能可控的状态的。
以上就是个人学习成果,若是有什么我没有思考到的地方或是文章内存在错误,欢迎与我分享。
相关文章推荐: