8. Callables and Futures
实现多线程时一般用的是Runnable接口,但是他有一个问题就是他没有参数和返回值,所以当执行一个线程需要返回一个值的时候就不是很
方便了。Callable接口和Runnable差不多,但是他提供了参数和返回值:
public interface Callable<V>
{
V call() throws Exception;
}
而Future接口可以保留异步执行的值:
public interface Future<V>
{
V get() throws . . .;
V get(long timeout, TimeUnit unit) throws . . .;
void cancel(boolean mayInterrupt);
boolean isCancelled();
boolean isDone();
}
FutureTask可以很方便的把Callable转换成Future和Runnable:
Callable<Integer> myComputation = . . .;
FutureTask<Integer> task = new FutureTask<Integer>(myComputation);
Thread t = new Thread(task); // it's a Runnable
t.start();
. . .
Integer result = task.get(); // it's a Future
9.用Executors创建线程池
用线程池有两个好处:1. 减少创建线程的开销。2. 控制线程的数量。
EXecutors提供了一些方法可以很方便的创建线程池:
newCachedThreadPool
New threads are created as needed; idle threads are kept for 60 seconds.
newFixedThreadPool
The pool contains a fixed set of threads; idle threads are kept indefinitely.
newSingleThreadExecutor
A "pool" with a single thread that executes the submitted tasks sequentially.
newScheduledThreadPool
A fixed-thread pool for scheduled execution.
newSingleThreadScheduledExecutor
A single-thread "pool" for scheduled execution.
在使用Executors时,先调用这些静态方法创建线程池,得到一个ExecutorService对象,然后用这个对象的submit方法提交你的
Runnable或是Callable对象。
Future<?> submit(Runnable task)
Future<T> submit(Runnable task, T result)
Future<T> submit(Callable<T> task)
如果不再需要任何提交,就用shutdown方法来关闭线程池。