使用 Callable 时,Integer 如何自动装箱到 Future<Integer> 中?

How does Integer become autoboxed into Future<Integer> when using Callable?

我正在使用并发 API,我正在将 classinstance 传递给 submit(Callable<T>) 方法以执行单线程任务。

import java.util.concurrent.*;

class myCallableClass implements Callable<Integer> { // Implementation of the Callable<T> interface
    @Override
    public Integer call() throws Exception { // Clearly returning an Integer here, and yet ...
        System.out.println("1: doing first task");
        Thread.sleep(11 * 1000);
        return WaitingForAllTasksToFinish.counter + 2;
    }
}

public class WaitingForAllTasksToFinish {
    static int counter = 2;

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService service = null;
        try {
            service = Executors.newSingleThreadExecutor();
            Future<Integer> result 
            = service.submit(new myCallableClass()); // ... it can be assigned to Future<Integer> here!
            System.out.println(result.get()); // and I can use .get() which is a Future<T> method!
        } finally {
            if (service != null) service.shutdown();
        }
    }

}

为了判断是否有'autobox',我尝试将Integer赋值给一个Future<Integer>,但是编译报错:

Future<Integer> x = Integer.valueOf(4); // Type mismatch: cannot convert from Integer to Future<Integer>

问题:如果 submit(Callable<T>) 方法返回一个 Integer,我可以假设它可以分配给 Future i 吗?如果是这样,是否有幕后发生的事情来实现这一目标?

编辑:

创建 Future 不是自动装箱。 Java 语言并不像它了解 Integer/int 那样“了解”Future。自动装箱特别是语言(编译器)在适当的时候自动将 int 转换为 Integer

这里发生的是 API(在本例中为 ExecutorService.submit)在传入 Callable<T> 时将 return 为 Future<T>。 ExecutorService 将安排任务执行,return 你可以使用句柄(Future)查询任务是否完成,并在必要时从中获取结果。

请注意, 一个自动装箱实例发生在您的代码中,但那是在第

return WaitingForAllTasksToFinish.counter + 2;

由于方法定义为 return 和 Integer 但表达式 WaitingForAllTasksToFinish.counter + 2int 类型,Java 将自动转换 intInteger ,但这与创建 Future.

无关