get(long timeout, TimeUnit unit)用来获取执行结果,如果在指定时间内,还没获取到结果,就直接返回null。
而FutureTask即可以作为Runnable又可以作为Future,这样就既可以用ExecutorService的execute执行任务,也可以用ExecutorService的submit提交任务。
例子1:
Callable、Future实现子线程执行任务,并返回结果,主线程等待子线程结果在进行其他逻辑。(多个子线程并行执行任务,主线程做合并处理参见CompletionService用法 )
1 import java.util.concurrent.Callable; 2 import java.util.concurrent.ExecutionException; 3 import java.util.concurrent.ExecutorService; 4 import java.util.concurrent.Executors; 5 import java.util.concurrent.Future; 6 7 public class CallableAndFuture1 { 8 9 public static void main(String[] args) {10 ExecutorService service = Executors.newSingleThreadExecutor();11 12 Future<Integer> future = service.submit( new Callable<Integer>() {13 14 @Override15 public Integer call() throws Exception {16 System. out.println("子线程" + Thread.currentThread().getName() + "在进行计算");17 Thread. sleep(3000);18 19 int sum = 0;20 for (int i = 0; i < 100; i++) {21 sum += i;22 }23 return sum;24 }25 });26 27 System. out.println("主线程" + Thread.currentThread ().getName() + "在执行任务" );28 29 try {30 System. out.println("子线程运行结果" + future.get());31 } catch (InterruptedException e) {32 e.printStackTrace();33 } catch (ExecutionException e) {34 e.printStackTrace();35 }36 37 System. out.println("所有任务执行完毕" );38 39 }40 }