【发布时间】:2018-12-26 07:23:33
【问题描述】:
我实现了一个虚拟计数器,只是在 0-100 之间上下计数。
很简单,工厂提供了一个实现Runnable的VirtualCounter。
@Getter
@Setter
public class VirtualTimer implements Runnable {
private int currentValue = ThreadLocalRandom.current().ints(0, 100).findFirst().getAsInt();
private boolean countingUp;
private VirtualTimer() {
}
@Override
public void run() {
while (true) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (countingUp) {
if (currentValue == 100) {
countingUp = false;
currentValue--;
} else
currentValue++;
} else {
if (currentValue == 0) {
countingUp = true;
currentValue++;
} else
currentValue--;
}
System.out.println("CurrentValue: " + currentValue);
}
}
public static class CounterFactory {
public static VirtualTimer getNewCounter() {
return new VirtualTimer();
}
}
}
起作用的是 Runnable 的这种用法
Runnable runnable = VirtualTimer.CounterFactory.getNewCounter();
Thread test = new Thread(runnable);
test.start();
不起作用是这样的:
Thread test = new Thread(VirtualTimer.CounterFactory::getNewCounter);
test.start();
所以我知道如何让它运行,但是我真的很想了解为什么第一次尝试有效而第二次无效。
第二个的 run 方法永远不会被调用。调试器不由明白。对这种行为有什么好的解释吗?
谢谢
【问题讨论】:
-
我不明白为什么它应该首先工作。
标签: java java-8 function-expression supplier