1.线程池的继承关系图
2.线程池架构图
3.部分结构和类的分析
3.1Executor
从上图可以看出Executor线程池的根接口,代码如下:
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 <tt>Executor</tt> 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);
}
3.2 ExecutorService
ExecutorService是继承于Executor的一个接口,该接口增加了一下新的方法,部分方法列表如下:
void shutdown();//依次关闭之前提交的任务,不在接受新的任务
List<Runnable> shutdownNow();//试图停止所有正在执行的任务,终止等待的任务,并且返回所有的等待的任务
boolean isShutdown();//判断执行器是否停止,如果停止返回true
boolean isTerminated();//如果关闭后所有任务都已完成,则返回 true。注意,除非首先调用 shutdown 或 shutdownNow,否则 isTerminated 永不为 true。
boolean awaitTermination(long timeout, TimeUnit unit)//请求关闭、发生超时或者当前线程中断,无论哪一个首先发生之后,都将导致阻塞,直到所有任务完成执行
Future<?> submit(Runnable task);//提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。该 Future 的 get 方法在 成功 完成时将会返回 null。
3.3 AbstractExecutorService是一个抽象类,它默认实现了ExecutorService接口。
3.4 ThreadPoolExecutor线程池实现类,继承AbstractExecutorService
常用方法:
public void execute(Runnable command)//在未来的某个时候执行,这个任务可能在新线程中执行或者在线程池中的线程执行
private boolean addWorker(Runnable firstTask, boolean core)//添加工作线程
public void shutdown()//上面接口的实现
public List<Runnable> shutdownNow()//上面接口的实现
3.5ScheduledExecutorService
ScheduledExecutorService是一个接口,它继承于于ExecutorService。它相当于提供了”延时”和”周期执行”功能的ExecutorService。
方法列表
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);//在延迟之后,创建和执行一次操作
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);//在延迟之后,创建并执行一个ScheduledFuture
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);//创建一个周期性的动作
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit);//在开始延迟,创建周期性的动作
3.6 ScheduledThreadPoolExecutor
一个具有延迟,周期性的线程池,但多线程时,ScheduledThreadPoolExecutor比java.util.Timer更好的伸缩性。
方法类表跟上面接口一样
4.简单实例
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolTest
{
public static void main(String[] args)
{
ExecutorService pool = Executors.newFixedThreadPool(2);
for(int i=0; i<5; i++){
pool.execute(new Runnable()
{
@Override
public void run()
{
System.out.println(Thread.currentThread().getName());
}
});
}
pool.shutdown();//记住关闭
}
}
pool-1-thread-1
pool-1-thread-1
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
总结:主要是对线程池的整体结构进行分析,后续将对具体的线程池进行深入分析。