铁文整理
14.9 执行器
构建一个新的线程是有一定代价的,因为涉及与操作系统的交互。如果程序中创建了大量的生命期很短的线程,应该使用线程池。一个线程池中包含许多准备运行的空闲线程。将Runnable对象交给线程池,就会有一个线程调用run方法。当run方法退出时,线程不会死亡,而是在池中准备为下一个请求提供服务。
另一个使用线程池的理由是减少并发线程的数目。创建大量线程会大大降低性能甚至使虚拟机崩溃。如果有一个会创建许多线程的算法,应该使用一个线程数“固定的”线程池以限制并发线程的总数。
执行器(Executor)类有许多静态工厂方法用来构建线程池,表14-2中对这些方法进行了汇总。
表14-2 执行者工厂方法
方法 | 描述 |
newCachedThreadPool | 必要时创建新线程;空闲线程会被保留60秒 |
newFixedThreadPool | 该池包含固定数量的线程,空闲线程会一直被保留 |
newSingleThreadExecutor | 只有一个线程的“池”,该线程顺序执行每一个提交的任务(类似于Swing事件分配线程) |
newScheduledThreadPool | 用于预定执行而构建的固定线程池,替代java.util.Timer |
newSingleThreadScheduledExecutor | 用于预定执行而构建的单线程“池” |
14.9.1 线程池
先来看一下表14-2中的3个方法。在第14.9.2节中,我们讨论其余的方法。newCachedThreadPool方法构建了一个线程池,对于每个任务,如果有空闲线程可用,立即让它执行任务,如果没有可用的空闲线程,则创建一个新线程。newFixedThreadPool方法构建一个具有固定大小的线程池。如果提交的任务数多于空闲的线程数,那么把得不到服务的任务放置到队列中。当其他任务完成以后再运行它们。newSingleThreadExecutor是一个退化了的大小为1的线程池:由一个线程执行提交的任务,一个接着一个。这3个方法返回实现了ExecutorService接口的ThreadPollExecutor类的对象。
可用下面的方法之一将一个Runnable对象或Callable对象提交给ExecutorService:
Future<?> submit(Runnable task)
Future<T> submit(Runnable taskh, T result)
Future<T> submit(Callable<T> task)
该池会在方便的时候尽早执行提交的任务。调用submit时,会得到一个Future对象,可用来査询该任务的状态。
第一个submit方法返回一个奇怪样子的Future<?>。可以使用这样一个对象来调用isDone、cancle或isCancelled。但是,get方法在完成的时候只是简单地返回null。
第二个版本的submit也提交一个Runnable,并且Future的get方法在完成的时候返回指定的result。
第三个版本的submit提交一个Callable,并且返回的Future对象将在计算结果准备好的时候得到它。
当用完一个线程池的时候,调用shutdown。该方法启动该池的关闭序列。被关闭的执行器不再接受新的任务。当所有任务都完成以后,线程池中的线程死亡。另—种方法是调用shutdownNow。该池取消尚未开始的所有任务并试图中断正在运行的线程。
下面总结了在使用连接池时应该做的事:
-
调用Executors类中静态的方法newCachedThreadPool或newFixedThreadPool。
-
调用submit提交Runnable或Callable对象。
-
如果想要取消一个任务,或如果提交Callable对象,那就要保存好返回的Future对象。
-
当不再提交任何任务时,调用shutdown。
例如,前面的程序例子产生了大量的生命期很短的线程,每个目录产生一个线程。例14-12中的程序使用了一个线程池来运行任务。
出于信息方面的考虑,这个程序打印出执行中池中最大的线程数。但是不能通过ExecutorService这个接口得到这一信息。因此,必须将该pool对象转型为ThreadPoolExecutor类对象。
例14-12 ThreadPoolTest.java
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
/**
* @version 1.0 2004-08-01
* @author Cay Horstmann
*/
public class ThreadPoolTest {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
System.out.print("Enter base directory (e.g. /usr/local/jdk5.0/src): ");
String directory = in.nextLine();
System.out.print("Enter keyword (e.g. volatile): ");
String keyword = in.nextLine();
ExecutorService pool = Executors.newCachedThreadPool();
MatchCounter counter = new MatchCounter(new File(directory), keyword, pool);
Future<Integer> result = pool.submit(counter);
try {
System.out.println(result.get() + " matching files.");
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
}
pool.shutdown();
int largestPoolSize = ((ThreadPoolExecutor) pool).getLargestPoolSize();
System.out.println("largest pool size=" + largestPoolSize);
}
}
/**
* This task counts the files in a directory and its subdirectories that contain
* a given keyword.
*/
class MatchCounter implements Callable<Integer> {
/**
* Constructs a MatchCounter.
*
* @param directory
* the directory in which to start the search
* @param keyword
* the keyword to look for
* @param pool
* the thread pool for submitting subtasks
*/
public MatchCounter(File directory, String keyword, ExecutorService pool) {
this.directory = directory;
this.keyword = keyword;
this.pool = pool;
}
public Integer call() {
count = 0;
try {
File[] files = directory.listFiles();
ArrayList<Future<Integer>> results = new ArrayList<Future<Integer>>();
for (File file : files)
if (file.isDirectory()) {
MatchCounter counter = new MatchCounter(file, keyword, pool);
Future<Integer> result = pool.submit(counter);
results.add(result);
} else {
if (search(file))
count++;
}
for (Future<Integer> result : results)
try {
count += result.get();
} catch (ExecutionException e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
}
return count;
}
/**
* Searches a file for a given keyword.
*
* @param file
* the file to search
* @return true if the keyword is contained in the file
*/
public boolean search(File file) {
try {
Scanner in = new Scanner(new FileInputStream(file));
boolean found = false;
while (!found && in.hasNextLine()) {
String line = in.nextLine();
if (line.contains(keyword))
found = true;
}
in.close();
return found;
} catch (IOException e) {
return false;
}
}
private File directory;
private String keyword;
private ExecutorService pool;
private int count;
}
API:java.util.concurrent.Executors 5.0
-
ExecutorService newCachedThreadPool():返回一个带缓存的线程池,该池在必要的时候创建线程,在线程空闲60秒之后终止线程。
-
ExecutorService newFixedThreadPool(int threads):返回一个线程池,该池中的线程数由参数指定。
-
ExecutorService newSingTeThreadExecutor():返回一个执行器,它在一个单个的线程中依次执行各个任务。
API:java.util.concurrent.ExecutorService 5.0
-
Future<T> submit(Callable<T> task)
-
Future<T> submit(Runnable taskh, T result)
-
Future<?> submit(Runnable task):提交指定的任务去执行。
-
void shutdown():关闭服务,会先完成已经提交的任务而不再接收新的任务。
API:java.util.concurrent.ThreadPoolExecutor 5.0
-
int getLargestPoolSize():返回线程池在该执行器生命周期中的最大尺寸。
14.9.2 预定执行
ScheduleExecutorService接口具有为预定执行或重复执行任务而设计的方法。它是一种允许使用线程池机制的java.util.Timer的泛化。Executors类的newScheduledThreadPool和newSingleThreadScheduledExecutor方法将返回实现了ScheduleExecutorService接口的对象。
可以预定Runnable或Callable在初始的延迟之后只运行—次。也可以预定一个Runnable对象周期性地运行。详细内容见API文档。
API:java.util.concurrent.Executors 5.0
-
ScheduledExecutorService newScheduledThreadPool(int threads):返回一个线程池,它使用给定的线程数来调度任务。
-
ScheduledExecutorService newSingleThreadScheduledExecutor():返回一个执行器,它在一个单独线程中调度任务。
API:java.util.concurrent.ScheduledExecutorService 5.0
-
ScheduledFture<V> schedule(Callable<V> task, long time, TimeUnit unit)
-
ScheduledFuture<?> schedule(Runnable task, long time, TimeUntt unit):预定在指定的时间之后执行任务。
-
ScheduledFuture<?> scheduIeAtFixedRate(Runnable task, long initialDelay, long period, TimeUnft unit):预定在初始的延迟结束后,周期性地运行给定的任务,周期长度是period。
-
ScheduledFuture<?> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit):预定在初始的延迟结束后周期性地给定的任务,在—次调用完成和下—次调用开始之间有长度为delay的延迟。
14.9.3 控制任务组
你已经了解了如何将一个执行器服务作为线程池使用,以提高执行任务的效率。有时,使用执行器有更有实际意义的原因,控制—组相关任务。例如,可以在执行器中使用shutdownNow方法取消所有的任务。
invokeAny方法提交所有对象到一个Callable对象的集合中,并返回某个已经完成了的任务的结果。无法知道返回的究竞是哪个任务的结果,也许是最先完成的那个任务的结果。对于搜索问题,如果你愿意接受任何一种解决方案的话,你就可以使用这个方法。例如,假定你对一个大整数进行因数分解。只要其中一个任务得到了答案,计算就可以停止了。
invokeAll方法提交所有对象到一个Callable对象的集合中并返回一个Future对象的列表,代表所有任务的解决方案。当计算结果可获得时,可以像下面这样对结果进行处理:
List<Callable<T>>tasks = ...;
List<Future<T>> results = executor.invokeAll(tasks);
for (Future<T> result : results)
processFurther(result.get());
这个方法的缺点是如果第一个任务恰巧花去了很多时间,则可能不得不进行等待。以结果按可获得的顺序保存起来更有实际意义。可以用ExecutorCompletionService来进行排列。
用常规的方法获得一个执行器。然后,构建一个ExecutorCompletionService,提交任务给完成服务(completion service)。该服务管理Future对象的阻塞队列,其中包含已经提交的任务的执行结果(当这些结果成为可用时)。这样一来,相比前面的计算,一个更有效的组织形式如下:
ExecutorCompletionService service = new ExecutorCompletionService(executor);
for (Callable<T> task : tasks)
service.submit(task);
for (int i = 0; i < tasks.size(); i++)
processFurther(service.take().get());
API:java.util.concurrent.ExecutorService 5.0
-
T invokeAny(Conection<Callable<T>> tasks)
-
T invokeAny(Collection<Callable<T>> tasks, long timeout, TimeUnit unit):执行给定的任务,返回其中一个任务的结果。第二个方法若发生超时,抛出一个TimeoutException异常。
-
List<Future<T>> invokeAll(Collection<Callable<T>> tasks)
-
List<Future<T>> invokeAll(Collection<Callable<T>> tasks, long timeout, TimeUnit unit):执行给定的任务,返回所有任务的结果,第二个方法若发生超时,抛出一个了TimeoutException异常。
API:java.util.concurrent.ExecutorCompletionService 5.0
-
ExecutorCompletionService(Executor e):构建一个执行器完成服务来收集给定执行器的结果。
-
Future<T> submit(Callable<T> task)
-
Future<T> submit(Runnable task, T result):提交一个任务给底层的执行器。
-
Future<T> take():移除下一个已完成的结果,如果没有任何已完成的结果可用则阻塞。
-
Future<T> poll()