【问题标题】:Runnable class is not exectued可运行类未执行
【发布时间】: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


【解决方案1】:

因为表达式VirtualTimer.CounterFactory::getNewCounter
Supplier<? extends Runnable> 类型,而不是 Runnable

【讨论】:

  • 哇,这就是 IntelliJ 在完成此操作后的建议: Thread test = new Thread(VirtualTimer.CounterFactory.getNewCounter()); IntelliJ 在那里做了一个错误的工作。泰!
猜你喜欢
  • 1970-01-01
  • 2011-12-08
  • 2015-12-19
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 2012-07-10
  • 2020-10-29
  • 1970-01-01
相关资源
最近更新 更多