user2533604
user2533604

Reputation: 665

Why start() is not working in my extension of Thread

I am getting output when i called run() through t.start(), but not getting same output through obj.start(). what may be the reason?

Can anyone explain this?

class Ex1 implements Runnable {

    int n;
    String s;

    public void run(){
        for(int i=1;i<=n;i++){
            System.out.println( s +"-->"+ i);
        }
    }   
}


class RunnableDemo extends Thread {

    Ex1 e;
    RunnableDemo(Ex1 e) {
        this.e = e;
    }

    public static void main(String[] args) {    

        Ex1 obj1 = new Ex1();
        Ex1 obj2 = new Ex1();

        obj1.n = 5;
        obj1.s = "abc";

        // Thread t = new Thread(obj1);
        // t.start();
        RunnableDemo obj = new RunnableDemo(obj1);
        obj.start();
    }
}

Upvotes: 1

Views: 138

Answers (3)

Terry Li
Terry Li

Reputation: 17268

The problem is that you didn't override the run method when making a subclass of Thread. Since the default run method does not do anything, you won't get any result.

Upvotes: 0

musical_coder
musical_coder

Reputation: 3896

You also need to add @Override to run():

@Override
public void run(){
    for(int i=1;i<=n;i++){
        System.out.println( s +"-->"+ i);
    }
} 

Upvotes: 0

Sinkingpoint
Sinkingpoint

Reputation: 7624

I believe that you need to call super in your RunnableDemo's constructor:

RunnableDemo(Ex1 e){
        super(obj);
        this.e = e;
}

This calls the super class's (Thread) constructor with the obj argument, so that the start method works as expected.

Without doing this, you are actually implictly calling super with no arguments, thus no runnable is set for the RunnableDemo instance.

Upvotes: 4

Related Questions