线程 参数 java_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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值