我们知道线程能通过继承Thread和实现Runnable接口来实现,但是,他们都有一个弊端,就是run之后不能有返回值,当然我们可以通过向线程中传入变量的方式解决,但是貌似又不总是那么可靠,还好,java给了我们另外的接口Callable和Future.
我们先来看看他们的结构:
<span style="font-size:14px;">public interface Callable<V>{
V call() throws Exception;
}
public interface Future<V>{
V get() throws Exception;
V get(long timeout, TimeUnit unit)throws Exception;
void cancle(boolean mayInterrput);
boolean isCancelled();
boolean isDone();
}</span>
在Callable中我们可以看到调用call的时候是可以返回V的,而Future是干嘛的呢,他可以用来保存异步计算的结果。
第一个get和被阻塞直至计算完成并返回结果,第二个假如超时,会抛出TImeoutException异常。
如果计算还在继续,isDone()会返回false,假如已经完成,则返回true.
cancle可以取消计算,如果还没开始则不会被运行,假如已经开始,且mayInterrupt为true,他会被中断。
java中还存在FutureTask包装器,可以将Callable转化成Future和Runnable.例如:
<span style="font-size:14px;">public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<Integer> callable = new ...;
FutureTask<Integer> task = new FutureTask<Integer>(callable);
Thread thread = new Thread(task);
thread.start();
Integer integer = task.get();
}</span>
好了,到了我感觉很牛逼的东西出场的时候了-----执行器
假如我们创建大量的线程,然后又终止他们系统是需要很大的花销的。那么我们可不可以复用他们呢,可以,调用线程池(thread pool)。
执行器(Executor)类有很多的工厂方法来构建线程池。以下是线程池的汇总:
newCachedThreadPool必要时创建新线程,空闲线程会被保留60秒
newFixedThreadPool该线程池包含固定数量的线程,空闲线程会一直被保留
newSingleThreadExecutor只有一个线程的“池”,该线程按照顺序执行每一个提交的任务
newScheduledThreadPool用于预定执行而构建的固定线程池,代替java.util.Timer
newSingleScheduledExecutor用于预定执行而创建的单线程“池”
接下来我们只说前三个。
他们都是实现了ExecutorService接口的ThreadPoolExecutor类,下面方法可以提交一个任务
<span style="font-size:14px;"> Future<?> submit(Runnable task);
Future<T> submit(Runnable task, T result);
Future<T> submit(Callable task);</span>
第一个,因为Runnable 自身不返回,而却没有足够信息制定返回的对象是什么,所以我们可以看见返回的是Future<?>,其实当调用Future的get时,只是简单的返回null而已,当然其他的方法依旧能用。
第二个,也是一个Runnable对象,但是用get时,会返回置顶的result对象。
第三个,传入一个Callable对象,并返回指定值。
当然在使用完一个线程池后记得shutdown.
下面我们来看一个示例:
<span style="font-size:14px;">class Counter implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + "counting");
int i;
for (i = 0; i < 60; i++){
if (i % 10 == 0){
System.out.println();
}
System.out.print(i + " ");
}
return i;
}
}
public class ForCallable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newCachedThreadPool();
Counter counter = new Counter();
Future<Integer> future = pool.submit(counter);
System.out.println(Thread.currentThread().getName() + ": i am sleeping");
Thread.sleep(5000);
System.out.println("get value:" + future.get());
pool.shutdown();
}
}
</span>