2017-08-01 53 views
2

我一直在研究由人編寫的例子Java代碼,面對下面的代碼片段:方法引用作爲Executor實現

Runnable runnable =() -> System.out.println("Thread name: " + Thread.currentThread().getName()); 

Executor executor; 

executor = Runnable::run; 
executor.execute(runnable); 

所以,我想不出在這種情況下,方法參考如何能夠實例化一個Executor,以及如果它沒有實現,怎麼可能調用execute(Runnable command)。總體而言,在這種情況下,方法參考在窗簾後面如何工作?

回答

3

Executor符合功能接口的定義,因爲它有一個抽象方法。即此一:

void execute(Runnable command) 

因此,我們需要爲了實現該功能界面是運行在一個Runnable並沒有返回值的方法。簡稱command -> command.run()Runnable::run,是一個可以做到這一點的方法的例子。

下面的代碼三個位是等效的:

executor = Runnable::run; 

executor = (Runnable command) -> command.run(); 

executor = new Executor() { 
    public void execute(Runnable command) { 
     command.run(); 
    } 
}