#Is it correct to start the thread inside its constructor, or is this a bad practice?

8 messages · Page 1 of 1 (latest)

ashen niche
#

Like this:

package com.pong.gamedisplay;

public class TimerThread extends Thread implements Runnable {

    private int secondsLeft;
    
    public TimerThread(int seconds) {
        secondsLeft = seconds;
        this.start();
    }
    
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException e) {}
        
        secondsLeft--;
        if (secondsLeft == 0) {
            this.interrupt();
        }
    }
    
    public int getSecondsLeft() {
        return secondsLeft;
    }
    
}

also is it redundant to implement Runnable in the TimerThread class if the parent class Thread already implements it? I am not getting any error no matter if I implement it to the TimerThreador not

woeful ridgeBOT
#

This post has been reserved for your question.

Hey @ashen niche! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

clever topaz
#

Yes, it is bad practice. And yes, you don't need to declare your class to implement Runnable when its parent class already does.

#

Your constructor should only do basic assignment stuff, never any complex logic that could have side-effects

#

because when someone does new TimerThread(), not knowing what your class does exactly, they're not gonna expect it to spawn a thread before you even call a method on the object.

ashen niche
#

alright, thanks for the help

woeful ridgeBOT
# ashen niche alright, thanks for the help

If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.