FutureTask
RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口,所以FutureTask既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
FutureTask代码举例
1 测试类-FutureTaskTest02
package com.sqq.future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
/**
* @description: Callable+FutureTask获取执行结果
* 可以看出RunnableFuture继承了Runnable接口和Future接口,而FutureTask实现了RunnableFuture接口。
* 所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。
* @author: shiqiangqiang
* @createDate: 2020/6/21
* @version: 1.0
*/
public class FutureTaskTest02 {
public static void main(String[] args) {
test02();
}
/**
* 第一种方式
*/
private static void test01(){
ExecutorService executor = Executors.newCachedThreadPool();
Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<>(task);
executor.submit(futureTask);
executor.shutdown();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主线程在执行任务");
try {
System.out.println("task运行结果" + futureTask.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
/**
* 第二种方式,注意这种方式和第一种方式效果是类似的,只不过一个使用的是ExecutorService,一个使用的是Thread
*/
private static void test02(){
Task task = new Task();
FutureTask<Integer> futureTask = new FutureTask<>(task);
Thread thread1 = new Thread(futureTask);
thread1.start();
try {
System.out.println("test02 task运行结果" + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("test02 所有任务执行完毕");
}
}
2 任务类-Task
package com.sqq.future;
import java.util.concurrent.Callable;
/**
* @description:
* @author: shiqiangqiang
* @createDate: 2020/6/21
* @version: 1.0
*/
public 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;
}
}
网友评论