Is there an interface similar to Callable but with arguments?

后端 未结 8 1597
小蘑菇
小蘑菇 2021-01-31 02:03

Is there an interface in Java similar to the Callable interface, that can accept an argument to its call method?

Like so:

public interface M         


        
8条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 02:20

    I just had the same issue. you can wrap any method to return a callable, and execute it's returned value. i.e.

     main {    
        Callable integerCallable = getIntegerCallable(400);
        Future future = executor.submit(integerCallable);
    }
    
    private Callable getIntegerCallable(int n) {
        return () -> {
                try {
                    TimeUnit.SECONDS.sleep(n);
                    return 123;
                } catch (InterruptedException e) {
                    throw new IllegalStateException("task interrupted", e);
                }
            };
    }
    

提交回复
热议问题