2016-12-27 85 views
1

我正在使一个方法在另一个线程中执行,因为它可能需要时间。但是,我想告诉来电者,操作将完成,如果成功。为此,我需要一个函数接口,它不返回任何东西(我不需要回调的结果)并传递布尔值。返回void并传递一个布尔参数的函数接口

示例代码:

public boolean send(Command command) { 
    try { 
     //long stuff 
     return true; 
    } catch(Exception ex) { 
     //logging error 
     return false; 
    } 
} 

public void sendAsync(Command command, MyCallback callback) { 
    new Thread(() -> { 
     boolean successful = send(command); 
     if(callback != null) 
      callback.call(successful); 
    }).start(); 
} 

喜欢的东西:

void call(boolean successful); 

是它已经存在于Java或做我必须做一个自己?

+0

你怎么知道手术很成功,如果它返回void? –

+0

@JakeMiller功能界面没有执行操作,只是报告操作是否成功并在实际操作后执行 – Winter

+0

有什么能阻止你自己定义它?如果你不需要结果,那么为什么你有一个参数? –

回答

4

方法void call(boolean successful)可以由表示为void accept(Boolean b),其被构建到java中。这将允许您避免必须创建自己的功能界面。

因此:

public void sendAsync(Command command, Consumer<Boolean> callback) { 
    new Thread(() -> { 
     boolean successful = send(command); 
     if(callback != null) 
      callback.accept(successful); 
    }).start(); 
}