Java 实例化执行器服务?

Java 实例化执行器服务?,java,multithreading,executorservice,Java,Multithreading,Executorservice,我了解到不能在Java中创建接口实例,但在以下代码中,Executors.newSingleThreadExecutor()返回一个ExecutorService实例,尽管ExecutorService是一个接口: //WorkerThread is a class that implements Runnable WorkerThread worker = new WorkerThread(); Executor exec=Executors.newSingleThreadExecutor()

我了解到不能在Java中创建接口实例,但在以下代码中,
Executors.newSingleThreadExecutor()
返回一个
ExecutorService
实例,尽管
ExecutorService
是一个接口:

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

您不能创建接口的实例,但可以创建实现该接口的类的实例

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

...

TheInterface test = new Test();
Executors.newSingleThreadExecutor()
返回类
FinalizableDelegatedExecutorService
的实例,该类实现了
ExecutorService
接口

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

...

TheInterface test = new Test();
公共静态执行器服务newSingleThreadExecutor(){ 返回新的FinalizableDelegatedExecutorService (新线程池执行器(1,1, 0L,时间单位为毫秒, 新建LinkedBlockingQueue()); }
当类实现某个接口时,可以将其实例化为该接口

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

...

TheInterface test = new Test();

ExecutorService
是一个接口,它扩展了
Executor
,它也是一个公开某些方法的接口。例如,在您的案例中,您可以在调用
Executors.newSingleThreadExecutor()时
它将返回
ThreadPoolExecutor的实例,您可以编写该执行器

Executor executor=Executors.newSingleThreadExecutor();
并且您只能调用Executor接口上可用的方法,即该接口上的
execute(Runnable命令)

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

...

TheInterface test = new Test();
对于不能使用接口直接创建的接口

Executor executor =new  Executor();//Not possible 
这是使用接口的最佳实践,所以您可以在不更改代码的情况下更改实现