get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
而FutureTask即可以作为Runnable又可以作为Future,这样就既可以用ExecutorService的execute执行任务,也可以用ExecutorService的submit提交任务。
例子1:
Callable、Future实现子线程执行任务,并返回结果,主线程等待子线程结果在进行其他逻辑。(多个子线程并行执行任务,主线程做合并处理参见CompletionService用法 )
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableAndFuture1 {
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
Future<Integer> future = service.submit( new Callable<Integer>() {
@Override
public Integer call() throws Exception {
System. out.println("子线程" + Thread.currentThread().getName() + "在进行计算");
Thread. sleep(3000);
int sum = 0;
for (int i = 0; i < 100; i++) {
sum += i;
}
return sum;
}
});
System. out.println("主线程" + Thread.currentThread ().getName() + "在执行任务" );
try {
System. out.println("子线程运行结果" + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System. out.println("所有任务执行完毕" );
}
}