java8: 请问这种写法,为什么可以作为线程对象参数传递?
// Java8可以把方法作为参数传递,但是 这个endOfWashing方法并没有返回线程对象啊?为什么可以编译通过呢?
代码如下,请看wash方法 下面那个参数this::endOfWashing :
private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class);
private final DelayProvider delayProvider;
private WashingMachineState washingMachineState;
public WashingMachine() {
this((interval, timeUnit, task) -> {
try {
Thread.sleep(timeUnit.toMillis(interval));
} catch (InterruptedException ie) {
ie.printStackTrace();
}
task.run();
});
}
/**
* Creates a new instance of WashingMachine using provided delayProvider. This constructor is used only for
* unit testing purposes.
*/
public WashingMachine(DelayProvider delayProvider) {
this.delayProvider = delayProvider;
this.washingMachineState = WashingMachineState.ENABLED;
}
public void wash() {
synchronized (this) {
LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), getWashingMachineState());
if (washingMachineState == WashingMachineState.WASHING) {
LOGGER.error("ERROR: Cannot wash if the machine has been already washing!");
return;
}
washingMachineState = WashingMachineState.WASHING;
}
LOGGER.info("{}: Doing the washing", Thread.currentThread().getName());
this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing);
}
/**
* Method responsible of ending the washing
* by changing machine state
*/
public synchronized void endOfWashing() {
washingMachineState = WashingMachineState.ENABLED;
LOGGER.info("{}: Washing completed.", Thread.currentThread().getId());
}
/**
* An interface to simulate delay while executing some work.
*/
public interface DelayProvider {
void executeAfterDelay(long interval, TimeUnit timeUnit, Runnable task);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
this::endOfWashing这个写法是java8的新语法。它不是调用endOfWashing,调用endOfWashing的语法是this.endOfWashing。
它不是把endOfWashing的返回值传给executeAfterDelay,而是把endOfWashing作为一个lambda表达式传给executeAfterDelay,类似c#里面的委托和javascript的回调函数。executeAfterDelay的内部会在某个时机调用作为回调函数的endOfWashing方法。
this::endOfWashing 等同于 () -> endOfWashing()
现在还有疑问吗?