executor框架
有任务、任务的执行、异步结果三部分组成。
executor框架包含有线程池的管理,还提供了线程工厂、队列以及拒绝策略等
任务
实现Runnable或者Callable接口
任务的执行
ThreadPoolExecutor和ScheduledThreadPoolExecutor
异步的结果
Future 接口以及 Future 接口的实现类 FutureTask 类都可以代表异步计算的结果。
如果当前同时运行的线程数量达到最大线程数量并且队列也已经被放满了任务时
Runnable
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("start............");
System.out.println("end............");
}
}
public class test1 {
private static final int CORE_POOL_SIZE = 6;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 2L;
public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new ThreadPoolExecutor.CallerRunsPolicy());
for(int i = 0; i < 10; i++){
Runnable worker = new MyRunnable();
executor.execute(worker);
}
executor.shutdown();
while(!executor.isTerminating()){
}
System.out.println("============");
}
}
Callable
class MyCallable implements Callable{
@Override
public String call() throws Exception {
return Thread.currentThread().getName() + "^_^_^_^_^_^_^_^_^_^_^_^_^_^";
}
}
public class test1 {
private static final int CORE_POOL_SIZE = 6;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 2L;
public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new ThreadPoolExecutor.CallerRunsPolicy());
List<Future<String>> futureList = new ArrayList<>();
Callable<String> callable = new MyCallable();
for(int i = 0; i < 10; i++){
Future<String> future = executor.submit(callable);
futureList.add(future);
}
for(Future f:futureList){
try {
System.out.println("====" + f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
while(!executor.isTerminating()){
}
System.out.println("============");
}
}
对比
| &bnsp; | Runnable | Callable |
|---|---|---|
| 返回值 | 无 | 有 |
| 抛出异常 | 不能 | 能 |
Executor执行过程
- 主线程创建或者实现Runnable/Callable接口
- 提交给ExecutorService执行
- 执行submit会返回一个Future对象
- 使用future接收返回
ThreadPoolExecutor 饱和策略定义:
|