javajava-8supplier

Runnable class is not exectued


I implemented a virtual counter, just counting up and down between 0-100.

It's very Simple, the factory supplies a VirtualCounter which implements Runnable.

@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();
        }
    }
}

What works is this usage of the Runnable

  Runnable runnable = VirtualTimer.CounterFactory.getNewCounter();
    Thread test = new Thread(runnable);
    test.start();

What doesn't work is this:

Thread test = new Thread(VirtualTimer.CounterFactory::getNewCounter);
        test.start();

So I know how to make this running but tbh I really want to understand why the first attempt works and the second not.

The run method of the second is just never called. Debugger could not help understanding. Any good explanation for this behavior?

Thanks


Solution

  • Because the expression VirtualTimer.CounterFactory::getNewCounter
    is of type Supplier<? extends Runnable>, not Runnable.