多线程08:《疯狂Java讲义》学习笔记——线程池
来源:互联网 发布:淘宝店铺运营方案设计 编辑:程序博客网 时间:2024/05/17 22:03
注:此文为学习《疯狂Java讲义》的笔记,因此内容全部来自于该书中。
当程序中需要创建大量生存期很短暂的线程,应该使用线程池。
线程池在系统启动时即创建大量空闲的线程,程序将一个Runnable对象或Callable对象传给线程池,线程池就会启动一个线程来执行它们的run()或call()方法,当run()或call()方法执行结束后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个Runnable对象的run()或call()方法。
1.Java 8改进的线程池
Java 5开始用Executors工厂类来产生线程池,该工厂类包含如下几个静态工厂方法来创建线程池。
Modifier and Type
Method and Description
static
ExecutorService
newCachedThreadPool()
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
static
ExecutorService
newCachedThreadPool(
ThreadFactory threadFactory)
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available, and uses the provided ThreadFactory to create new threads when needed.
static
ExecutorService
newFixedThreadPool(int nThreads)
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.
static
ExecutorService
newFixedThreadPool(int nThreads,
ThreadFactory threadFactory)
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue, using the provided ThreadFactory to create new threads when needed.
static
ScheduledExecutorService
newScheduledThreadPool(int corePoolSize)
Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
static
ScheduledExecutorService
newScheduledThreadPool(int corePoolSize,
ThreadFactory threadFactory)
Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
static
ExecutorService
newSingleThreadExecutor()
Creates an Executor that uses a single worker thread operating off an unbounded queue.
static
ExecutorService
newSingleThreadExecutor(
ThreadFactory threadFactory)
Creates an Executor that uses a single worker thread operating off an unbounded queue, and uses the provided ThreadFactory to create a new thread when needed.
static
ScheduledExecutorService
newSingleThreadScheduledExecutor()
Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.
static
ScheduledExecutorService
newSingleThreadScheduledExecutor(
ThreadFactory threadFactory)
Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically.
static
ExecutorService
newWorkStealingPool()
Creates a work-stealing thread pool using all available processors
as its target parallelism level.
static
ExecutorService
newWorkStealingPool(int parallelism)
Creates a thread pool that maintains enough threads to support the given parallelism level, and may use multiple queues to reduce contention.
ExecutorService代表尽快执行线程的线程池,程序只要将一个Runnable对象或Callable对象提交给该线程池,该线程池就会尽快执行该任务。
Modifier and Type
Method and Description
<T>
Future<T>
submit(
Callable<T> task)
Submits a value-returning task for execution and returns a Future representing the pending results of the task.
Future<?>
submit(
Runnable task)
Submits a Runnable task for execution and returns a Future representing that task.
<T>
Future<T>
submit(
Runnable task, T result)
Submits a Runnable task for execution and returns a Future representing that task.
ScheduledExecutorService代表可在指定延迟后或周期性地执行线程任务的线程池。
Modifier and Type
Method and Description
<V>
ScheduledFuture<V>
schedule(
Callable<V> callable, long delay,
TimeUnit unit)
Creates and executes a ScheduledFuture that becomes enabled after the given delay.
ScheduledFuture<?>
schedule(
Runnable command, long delay,
TimeUnit unit)
Creates and executes a one-shot action that becomes enabled after the given delay.
ScheduledFuture<?>
scheduleAtFixedRate(
Runnable command, long initialDelay, long period,
TimeUnit unit)
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay
theninitialDelay+period
, then initialDelay + 2 * period
, and so on.
ScheduledFuture<?>
scheduleWithFixedDelay(
Runnable command, long initialDelay, long delay,
TimeUnit unit)
Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.
用完一个线程池,调用该线程池的shutdown()方法,调用后不在接收新任务,但会把已经提交的任务完成。调用shutdownNow()方法,停止所有正在执行的活动任务,暂停处理正在等待的任务。
使用线程池来执行线程任务的步骤如下。
(1)调用Executors类的静态工厂方法创建一个ExecutorService对象,该对象代表一个线程池。
(2)创建Runnable实现类或Callable实现类的实例,作为线程执行任务。
(3)调用ExecutorService对象的submit()方法来提交Runnable实例或Callable实例。
(4)当不想提交任何任务时,调用ExecutorService对象的shutdown()方法来关闭线程池。
2.Java 8增强的ForkJoinPool
Java 7提供了ForkJoinPool来支持将一个任务拆分成多个“小任务”并行计算,再把多个“小任务”的结果合并成总的计算结果。ForkJoinPool是ExecutorService的实现类,是一种特殊的线程池。
构造方法:
Constructor and Description
ForkJoinPool()
Creates a ForkJoinPool
with parallelism equal to Runtime.availableProcessors()
, using the default thread factory, no UncaughtExceptionHandler, and non-async LIFO processing mode.
ForkJoinPool(int parallelism)
Creates a ForkJoinPool
with the indicated parallelism level, the default thread factory, no UncaughtExceptionHandler, and non-async LIFO processing mode.
ForkJoinPool(int parallelism,
ForkJoinPool.ForkJoinWorkerThreadFactory factory,
Thread.UncaughtExceptionHandler handler, boolean asyncMode)
Creates a ForkJoinPool
with the given parameters.
Modifier and Type
Method and Description
static
ForkJoinPool
commonPool()
Returns the common pool instance.
static int
getCommonPoolParallelism()
Returns the targeted parallelism level of the common pool.
可调用ForkJoinPool的submit(FoinJoinTask task)或invoke(ForkJoinPool)方法来执行指定任务。其中ForkJoinPool代表一个可以并行、合并的任务。ForkJoinTask是抽象类,其子类为RecursionAction(无返回值)和RecursiveTask(有返回值)。
- 多线程08:《疯狂Java讲义》学习笔记——线程池
- 多线程01:《疯狂Java讲义》学习笔记——线程概述
- 多线程02:《疯狂Java讲义》学习笔记——线程的创建和启动
- 多线程03:《疯狂Java讲义》学习笔记——线程的生命周期
- 多线程04:《疯狂Java讲义》学习笔记——控制线程
- 多线程05:《疯狂Java讲义》学习笔记——线程同步
- 多线程06:《疯狂Java讲义》学习笔记——线程通信
- 多线程07:《疯狂Java讲义》学习笔记——线程组和未处理的异常
- 多线程09:《疯狂Java讲义》学习笔记——线程相关类
- 《疯狂Java讲义》——多线程学习
- java线程总结(一)—java疯狂讲义学习笔记
- 《疯狂Java讲义》——控制线程
- 《疯狂Java讲义》学习笔记
- 疯狂java讲义笔记——数据类型
- 疯狂iOS讲义(下)——多线程第二天学习笔记
- 《疯狂JAVA讲义》学习笔记(一)
- 学习java疯狂讲义笔记(连载)
- 疯狂Java讲义-包装类学习笔记
- Sass和Compass安装
- js 获取浏览器高度和宽度值(多浏览器)
- Http Digest 认证
- CSDN发表文章图片显示是url
- 连接linux下crt输入ctrl+s很容易死机
- 多线程08:《疯狂Java讲义》学习笔记——线程池
- 设置web应用的 context root
- iOS 打包上传蒲公英安装失败及证书选择相关事项
- git fetch 和 git pull的区别
- 嵌入式系统 Boot Loader 技术内幕
- 出现( linker command failed with exit code 1)错误总结
- Raspberry Pi2/3引脚介绍
- 图片转文件流,文件流转图片
- Java设计模式(一) 设计模式初探——简单工厂和工厂方法模式