使用场景
FutureTask用于需要线程返回执行结果的情况
Callable与Runnable
Runnable
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
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()方法可以在线程结束后返回一个结果
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;
}
1.cancel:用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数mayInterruptIfRunning表示是否取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptIfRunning设置为false,不会取消恩物,返回false;如果任务还没有执行则无论mayInterruptIfRunning为true还是false,肯定返回true。如果任务已经完成则无论mayInterruptIfRunning为true还是false,一定会返回false;
2.isCancelled:如果此任务在正常完成之前被取消,则返回true。
3.isDone:如果此任务完成,则返回true。
4.get:等待任务完成,然后返回其结果。是一个阻塞方法
5.get(long timeout, TimeUnit unit):等待任务完成,然后返回其结果。如果在指定时间内,还没获取到结果,就直接返回null。
FutureTask
FutureTask是Future的唯一实现类(实现了RunnableFuture接口,而RunnableFuture接口继承了Runnable及Future)。有两个构造器,能返回结果的是第一个
public FutureTask(Callable<V> callable) {
}
public FutureTask(Runnable runnable, V result) {
}
代码
测试代码
public class FutureTaskTest {
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("所有任务执行完毕");
}
static 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;
}
}
}
结果
子线程在进行计算
主线程在执行任务
task运行结果4950
所有任务执行完毕