Search code examples
javamultithreadingrunnablecountdown

Java Countdown with thread


I have written a class in java which for a countdown clock. My class looks like this:

public class CountDown implements Runnable {

    ...

    @Override
    public void run() {

        // The functionality of the clock.

    }

    ...

}

Now, when I want to run a countdown from another class, I use this code

(new Thread(new CountDown(10))).start;

My question is:

Would it be better if I changed the class like this:

public class CountDown {

    ...

    public void start() {

        new Thread(new Runnable(){

            @Override
            public void run(){

                // The functionality of the clock.

            }

        ).start();

    }

    ...

}

And then call it from another class like this:

new CountDown(10).start();

Solution

  • I believe your first code snippet is the preferred solution, because you are not committing to a particular implementation. Thread is not the only implementation of Runnable (e.g. TimerTask, FutureTask, etc).

    By having your CountDown use Thread in the implementation, you take away a great amount of control from anyone who uses your CountDown. See "implements Runnable" vs. "extends Thread"