实例化 ExecutorService?

Instantiating ExecutorService?

我读到不能在 Java 中创建接口的实例,但在下面的代码中,Executors.newSingleThreadExecutor() returns 一个 ExecutorService 实例,尽管事实上ExecutorService 是一个接口:

//WorkerThread is a class that implements Runnable
WorkerThread worker = new WorkerThread();
Executor exec=Executors.newSingleThreadExecutor();
exec.execute(worker);

您不能创建接口的实例,但您当然可以创建实现该接口的 class 的实例。

Executors.newSingleThreadExecutor() returns class FinalizableDelegatedExecutorService 的一个实例,它实现了 ExecutorService 接口。

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

当 class 实现某个接口时,它可以被实例化为该接口。

interface TheInterface {}
class Test implements TheInterface {}

...

TheInterface test = new Test();

ExecutorService 是一个接口并扩展了 Executor 这也是一个公开某些方法的接口。例如,您可以在调用 Executors.newSingleThreadExecutor() 时返回ThreadPoolExecutor 的实例,它实现了 Executor,所以你可以写 .

Executor executor=Executors.newSingleThreadExecutor();

并且您只能调用 Executor 接口上可用的方法,即该接口上的 execute(Runnable command)

对于不能直接使用接口创建的接口

Executor executor =new  Executor();//Not possible 

最佳做法是使用接口,这样您就可以在不更改代码的情况下更改实现