我实现了一个虚拟计数器,只是在 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 方法从未被调用。调试器不禁理解了。对于这种行为有什么好的解释吗?
谢谢
VirtualTimer.CounterFactory::getNewCounter
属于
Supplier<? extends Runnable>
类型,而不是
Runnable
。