赞
踩
Java中创建线程的方法有四种,分别为继承Thread类,实现Runnable接口,实现Callable接口和通过线程池。在实际开发中,我们最常用的就是线程池的方法,因为利用线程池我们可以重复利用线程,减少每次创建线程所带来的额外开销;同时使用线程池也方便我们维护管理线程信息;此外,线程池的存在也可以帮助我们避免出现因为代码bug导致的无限创建线程导致系统资源耗尽等问题。
Java中通过使用ThreadPoolExecutor来创建管理线程池,而Spring框架中使用ThreadPoolTaskExecutor管理线程池,这是两个不同的组件,但spring中的ThreadPoolTaskExecutor的核心处理逻辑还是Java中的ThreadPoolExecutor,只是对其进行封装使得其可以成为Bean,交由Spring Context进行管理。
接下来,让我们来了解一下Java中的线程池ThreadPoolExecutor。
ThreadPoolExecutor类继承AbstractExecutorService类,实现ExecutorService,ExecutorService
接口,下面让我们先看一下这两个接口都定义了什么方法:
- public interface Executor {
-
- /**
- * Executes the given command at some time in the future. The command
- * may execute in a new thread, in a pooled thread, or in the calling
- * thread, at the discretion of the {@code Executor} implementation.
- *
- * @param command the runnable task
- * @throws RejectedExecutionException if this task cannot be
- * accepted for execution
- * @throws NullPointerException if command is null
- */
- void execute(Runnable command);
- }
- public interface ExecutorService extends Executor {
-
-
- void shutdown();
-
- List<Runnable> shutdownNow();
-
-
- boolean isShutdown();
-
-
- boolean isTerminated();
-
- boolean awaitTermination(long timeout, TimeUnit unit)
- throws InterruptedException;
-
-
- <T> Future<T> submit(Callable<T> task);
-
-
- <T> Future<T> submit(Runnable task, T result);
-
- Future<?> submit(Runnable task);
-
-
- <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
- throws InterruptedException;
-
- <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
- long timeout, TimeUnit unit)
- throws InterruptedException;
-
-
- <T> T invokeAny(Collection<? extends Callable<T>> tasks)
- throws InterruptedException, ExecutionException;
-
-
- <T> T invokeAny(Collection<? extends Callable<T>> tasks,
- long timeout, TimeUnit unit)
- throws InterruptedException, ExecutionException, TimeoutException;
- }
可以看出,Executor接口只定义了一个提交线程的方法,而ExecutorSrevice方法则基础Executor并扩展了它的功能,ExecutorSrevice中的方法看名字大多数也可以看出来,在此我们不做赘述,而ExecutorSrevice中的方法,AbstractExecutorService类都进行了默认的实现,下面我们来看一下AbstractExecutorService这个类中部分方法的实现:
- public abstract class AbstractExecutorService implements ExecutorService {
-
-
- protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
- return new FutureTask<T>(runnable, value);
- }
-
-
- protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
- return new FutureTask<T>(callable);
- }
-
-
- public Future<?> submit(Runnable task) {
- if (task == null) throw new NullPointerException();
- RunnableFuture<Void> ftask = newTaskFor(task, null);
- execute(ftask);
- return ftask;
- }
-
-
- public <T> Future<T> submit(Runnable task, T result) {
- if (task == null) throw new NullPointerException();
- RunnableFuture<T> ftask = newTaskFor(task, result);
- execute(ftask);
- return ftask;
- }
-
-
- public <T> Future<T> submit(Callable<T> task) {
- if
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。