知乎专栏 |
package cn.netkiller.test; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test { private final ExecutorService executor = Executors.newSingleThreadExecutor(); public Future<Integer> calculate(Integer input) { return executor.submit(() -> { System.out.println("Calculating..." + input); Thread.sleep(1000); return input * input; }); } public static void main(String[] args) throws InterruptedException, ExecutionException { Test test = new Test(); Future<Integer> future = test.calculate(12); Integer value = future.get(); System.out.println(value); } }
设置超时时间
value = future.get(500, TimeUnit.MILLISECONDS);
设置超时时间
value = future.get(500, TimeUnit.MILLISECONDS);
取消运行
boolean canceled = future.cancel(true);
判断是否完成
while(!future.isDone()) { System.out.println("Calculating..."); Thread.sleep(300); }
ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future1 = executor.submit(() -> "AAA"); Future<String> future2 = executor.submit(() -> "BBB"); Future<String> future3 = executor.submit(() -> "CCC"); Stream<String> stream = Stream.of(future1, future2, future3) .map(func -> { // System.out.println(Thread.currentThread().getName()); try { return func.get(5L, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (TimeoutException e) { throw new RuntimeException(e); } }).filter(Objects::nonNull); stream.forEach(System.out::println);