线程回顾 3

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方法来关闭线程池。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值