Java 未执行可运行类
我实现了一个虚拟计数器,只需在0-100之间进行上下计数 这很简单,工厂提供了一个实现Runnable的VirtualCounterJava 未执行可运行类,java,java-8,function-expression,supplier,Java,Java 8,Function Expression,Supplier,我实现了一个虚拟计数器,只需在0-100之间进行上下计数 这很简单,工厂提供了一个实现Runnable的VirtualCounter @Getter @Setter public class VirtualTimer implements Runnable { private int currentValue = ThreadLocalRandom.current().ints(0, 100).findFirst().getAsInt(); private boolean co
@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类型我不明白为什么它应该首先工作。哇,这是IntelliJ在完成这个之后建议的:线程测试=新线程(VirtualTimer.CounterFactory.getNewCounter());IntelliJ在那里做了一个错误的工作。泰!