一)展示他们的整体关系 ExecutorService extends Executor 注意这里的 Executor 是一个接口
二)
1.public class ThreadPoolExecutor extends AbstractExecutorService 继承了 AbstractExecutorService 抽象类
2.public abstract class AbstractExecutorService implements 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 <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);
}
该接口仅有一个
1)java.util.concurrent 包中 Executor查看 jdk 1.7.0_80 为一个接口,该接口中定义了一个无返回值的execute 方法 ,参数类型为Runnable
2)ExecutorService 接口中定义的12个方法中经常使用的方法有三个
1.Future<?> submit(Runnable task);使用起来很方便只要将新建的线程循环加入变可
2.void shutdown();
3.boolean isTerminated();
3)public class Executors 类 在使用 java 原生的线程池中 该类的静态方法提供了创建不同形式的线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
以newFixedThreadPool 为例(其他方法类似)根据源码可以看出 new 了一个
ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()) 类型的对象
1.public class ThreadPoolExecutor extends AbstractExecutorService 继承了 AbstractExecutorService 抽象类
2.public abstract class AbstractExecutorService implements ExecutorService 实现了 ExecutorService 接口
3 所以在调用的时候写出
ExecutorService executer = Executors.newFixedThreadPool(nThreads);
for(int i = 0 ;i<10 ;i++) {
Runnable t = new TestThread();
executer.submit(t);
}
executer.shutdown();//告诉线程池不在提交了,不调用此方法线程池一直等待,不会结束
//如果不用判断是否结束 到这里便可
//如果需要判断线程池里的所有线程都要结束才执行后面的代码就要
while(true) {
if(executer.isTerminated()) {
break;
}
try {
Thread.sleep(200l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
的时候实际是调用ThreadPoolExecutor 继承来自抽象类 AbstractExecutorService 实现 ExecutorService 中的代码