代码之家  ›  专栏  ›  技术社区  ›  s.ahmad

实例化ExecutorService?

  •  0
  • s.ahmad  · 技术社区  · 9 年前

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

    //WorkerThread is a class that implements Runnable
    WorkerThread worker = new WorkerThread();
    Executor exec=Executors.newSingleThreadExecutor();
    exec.execute(worker);
    
    3 回复  |  直到 9 年前
        1
  •  0
  •   Eran    9 年前

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

    Executors.newSingleThreadExecutor() 返回类的实例 FinalizableDelegatedExecutorService ,它实现了 ExecutorService

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

    当一个类实现某个接口时,可以将其实例化为该接口。

    interface TheInterface {}
    class Test implements TheInterface {}
    
    ...
    
    TheInterface test = new Test();
    
        3
  •  0
  •   gati sahu    9 年前

    ExecutorService 是一个接口并扩展 Executor Executors.newSingleThreadExecutor() 它正在返回的实例 ThreadPoolExecutor 哪一个执行器,你可以写。

    Executor executor=Executors.newSingleThreadExecutor();
    

    execute(Runnable command) 在该界面上。

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

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