通常我们比较清楚的也比较常见的线程实现方式都是一下两种:
- 继承Thread类
- 实现Runnable接口
这两个都有一个缺点就是在执行完之后无法获取执行结果,如果非要获取执行结果,只有通过共享变量或者使用线程通信的方式,但是这样的话是比较麻烦的。
jdk1.5之后,就提供了Callable和Future,通过他们可以在任务执行完成之后获取执行结果。
Runnable和Callable
以下是runnalbe的实现方法:
public interface Runnable {
public abstract void run();
}
显然Runable中只有一个run方法,并且返回值为void,因此没法获取返回值。
再看Callable:
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
可以看到这是一个泛型接口,call返回的类型就是传入的v型,Callable的使用一般是配合ExecutorService来使用的,在ExecutorService中声明了有若干个submit方法的重载体:
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);
案例介绍:
public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
Future<Integer> result = executor.submit(task);
executor.shutdown();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主线程在执行任务");
try {
System.out.println("task运行结果"+result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for(int i=0;i<100;i++)
sum += i;
return sum;
}
}
Future和FutureTask
先来看看Future的源码:
public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);
boolean isCancelled();
boolean isDone();
V get() throws InterruptedException, ExecutionException;
V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
- cancel:取消任务
- isCancelled:判断任务是否取消
- isDone:判断任务是否完成
- get:获取任务执行的结果,如果任务还没有执行完,这个方法会一直阻塞
- get(timeout,unit):获取任务的执行结果,如果指定时间内任务还没有执行完,那么返回null
因为Future是一个接口,无法创建对象,因此就有了FutureTask:
public class FutureTask<V> implements RunnableFuture<V>
下面来看看RunnableFuture接口的定义:
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
可以看到RunnableFuture继承了Runnable和Future,因此它既可以作为Runnable被线程执行,又可以作为Callable获取返回值。
FutureTask提供了两个构造器:
public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}
事实上,FutureTask也是Future唯一的实现类。
案例介绍:
public class Test {
public static void main(String[] args) {
//第一种方式
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
executor.submit(futureTask);
executor.shutdown();
//第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
/*Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
Thread thread = new Thread(futureTask);
thread.start();*/
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主线程在执行任务");
try {
System.out.println("task运行结果"+futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("子线程在进行计算");
Thread.sleep(3000);
int sum = 0;
for(int i=0;i<100;i++)
sum += i;
return sum;
}
}
更多多线程并发编程可以参考如下技术分享: http://www.cnblogs.com/dolphin0520/category/602384.html