Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

10.8. Future

		
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);
}		
		
		

10.8.1. Future + Stream 管理一组线程

			
		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);			
			
			

10.8.2. Future + ExecutorService

			
public class OldConcurrentService {
    privatefinal ExecutorService executor = Executors.newFixedThreadPool(2);

    public Map<String, Object> getPageData(String userId) throws Exception {
        // 1. 提交两个异步任务
        Future<String> userFuture = executor.submit(() -> fetchUserInfo(userId));
        Future<String> productFuture = executor.submit(() -> fetchProductList());

        // 2. 等待并获取结果,异常处理非常棘手
        try {
            String userInfo = userFuture.get(2, TimeUnit.SECONDS);
            String productList = productFuture.get(2, TimeUnit.SECONDS);
            
            // 3. 组合结果
            return Map.of("user", userInfo, "products", productList);
        } finally {
            // 4. 必须手动关闭线程池
            executor.shutdown();
        }
    }
    // 模拟API调用...
}