V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
maxwellwenjie894
V2EX  ›  问与答

Java 求助:为什么线程池中 ExecutorService.submit(Runnable task) 返回 Future<?> 而不是 Future<Void>?

  •  
  •   maxwellwenjie894 · Jul 29, 2021 · 1558 views
    This topic created in 1742 days ago, the information mentioned may be changed or developed.

    ExecutorService 有下面这个方法?

    Future<?> submit(Runnable task)

    但是 Future.get() 永远 return null,那下面这种方法声明是不是更好呢?

    Future<Void> submit(Runnable task)

    5 replies    2021-08-04 12:07:36 +08:00
    Honwhy
        1
    Honwhy  
       Jul 29, 2021
    我猜灵活可能是有好处的,
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    ExecutorService pool = Executors.newFixedThreadPool(1);
    String ret = "";
    FutureTask<String> task = new FutureTask<>(() -> {
    }, ret);
    Future<String> f1 = (Future<String>) pool.submit(task);
    Future<Void> f2 = (Future<Void>) pool.submit(task);
    System.out.println(f1.get());
    System.out.println(f2.get());
    pool.shutdown();
    }
    maxwellwenjie894
        2
    maxwellwenjie894  
    OP
       Jul 30, 2021
    谢谢回复,为什么不这样写呢?感觉范型在这里没啥用处啊
    Future f1 = pool.submit(task);
    Future f2 = pool.submit(task);
    System.out.println(f1.get());
    System.out.println(f2.get());
    uinity
        3
    uinity  
       Jul 30, 2021
    我个人觉得, 你得考虑到他是一个接口, 这个方法不一定只有这 AbstractExecutorService 这一种实现, 可能别的实现需要的返回结果不是 null 呢,你看下 ForkJoinTask 的实现.
    Maxwellwenjie
        4
    Maxwellwenjie  
       Aug 2, 2021
    非常感谢三楼的回复;那问题又来了,为什么 AbstractExecutorService 这种实现中 submit(Runnable task)方法要返回 Future<?>,返回 Future 不是更好吗?
    uinity
        5
    uinity  
       Aug 4, 2021
    @Maxwellwenjie 效果一样, 加上泛型更加规范一点吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4740 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 04:07 · PVG 12:07 · LAX 21:07 · JFK 00:07
    ♥ Do have faith in what you're doing.