线程池
线程池会在系统启动时即创建大量空闲线程,然后将一个Runnable/Callable对象提交给线程池,池就会分配/创建一个线程来执行他们的run()/call(),任务执行结束,该线程并不会死亡,而是再次返回池中变为空闲状态,等待执行下一个任务。线程池不仅可以避免每当有新任务就启动一个新线程带来的系统开销,而且可以有效控制系统中并发线程的数量,一旦系统中的线程超过一定数量,将导致系统性能剧烈下降,甚至JVM崩溃,而线程池可以设置最大线程数以防止线程数超标.java提供java.util.concurrent.Executors工厂类来生产线程池, 该工厂类提供如下静态方法:
方法 | 释义 |
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 newFixedThreadPool(int nThreads) | Creates a thread pool that reuses a fixed number of threads Operating off a shared unbounded queue. |
static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) | 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 ScheduledExecutorService newSingleThreadScheduledExecutor() | Creates a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically. |
方法 | 描述 |
Future submit(Callabletask) | 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. |
Futuresubmit(Runnable task, T result) | Submits a Runnable task for execution and returns a Future representing that task. |
Java为ExecutorService提供了一个java.util.concurrent.ThreadPoolExecutor实现类,该类有如下构造方法:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { // ...} 因此, 如果默认的线程池策略(如最[小/大]线程数/线程等待时间)不能满足我们的需求,我们可以自定义线程池策略.2. ScheduledExecutorService线程池是ExecutorService的子接口,代表可以在指定延迟后或周期性执行线程任务.它提供了如下方法来提交任务:
方法 |
V ScheduledFuture V schedule(Callable V callable, long delay, TimeUnit unit) |
ScheduledFuture ? schedule(Runnable command, long delay, TimeUnit unit) |
ScheduledFuture ? scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) |
ScheduledFuture ? scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) |
新闻热点
疑难解答