Java中的Executor框架提供了一组API,可用于优雅地管理多线程、线程池和异步调用。主要由三个接口组成:Executor、ExecutorService和ThreadPoolExecutor。
Executor接口
Executor是一个简单的接口,它提供了一种方法将任务提交到线程中执行。 其定义如下:
public interface Executor {
void execute(Runnable command);
}
该接口只包含一个方法execute,该方法使用Runnable对象表示需要执行的任务并将其提交到线程中。
ExecutorService接口
ExecutorService接口继承自Executor接口,提供了更多的方法,如可以提交一个Callable对象和在一定时间内获取一个Future对象等,其定义如下:
public interface ExecutorService extends Executor {
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
//其他方法...
}
其中,submit方法可以用来提交任务,submit(Runnable task, T result)方法还可以获取任务执行结果,submit(Callable
例子1:使用ExecutorService提交任务
ExecutorService executorService = Executors.newCachedThreadPool(); // 创建线程池
executorService.submit(new Runnable() {
@Override
public void run() {
// 执行任务
}
});
例子2:使用submit(Callable
ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建线程池
Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
// 执行任务
return "task done";
}
});
String result = future.get(); // 获取任务结果
System.out.println(result); // 输出 "task done"
ThreadPoolExecutor类
ThreadPoolExecutor 类是 ExecutorService 的默认实现,提供灵活的线程池管理。这个类提供了以下构造器:
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
参数解释:
- corePoolSize:线程池中的核心线程数。
- maximumPoolSize:线程池中的最大线程数。
- keepAliveTime:非核心线程空闲时间,超过这个时间,线程就会被回收。
- unit:keepAliveTime 的时间单位。
- workQueue:用于保存等待执行的任务的阻塞队列。
- threadFactory:创建新线程的工厂类。
- handler:拒绝策略。
例子3:创建一个FixedThreadPool
ExecutorService executorService = Executors.newFixedThreadPool(5); //等价于 ThreadPoolExecutor(5,5,0L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())
例子4:自己配置ThreadPoolExecutor
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 10, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(20));
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.prestartAllCoreThreads();
以上为Executor,ExecutorService,ThreadPoolExecutor等Java多线程中的重要数据类型之介绍.通过对这三种数据类型多线程管理器的了解可在实际项目中很好的规划多线程而有效的解决多线程问题。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:java中Executor,ExecutorService,ThreadPoolExecutor详解 - Python技术站