Java 实例化执行器服务?
我了解到不能在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()
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
这是使用接口的最佳实践,所以您可以在不更改代码的情况下更改实现