Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to call thread.start() instead of thread.run()? [duplicate]

Tags:

java

Possible Duplicate:
java thread - run() and start() methods

I made a program which uses threading---

public class ThreadTest{    
    public static void main(String[] args){     
        MyThread newthread=new MyThread();
        Thread t=new Thread(newthread);
        t.start();
        for(int x=0;x<10; x++){
            System.out.println("Main"+x)
        }
    }
} 

class MyThread implements Runnable{
    public void run(){
        for(int x=0; x<10; x++){
            System.out.println("Thread"+x);
        }
    }
}

Now my question is that ... why do we use the "Thread" class and create it's object and pass the "MyThread" calls in it's constructor? can't we call the run method of the "MyThread" object by creating it's object and calling the run method?

( i.e MyThread newthread=new MyThread(); and then newthread.run(); )

What's the reason for creating tread objects and passing the MyThread class in it?

like image 640
Iam APseudo-Intellectual Avatar asked Jan 18 '26 09:01

Iam APseudo-Intellectual


1 Answers

The MyThread class is not a thread. It is an ordinary class that implements Runnable and has a method called run.

If you call the run method directly it will run the code on the current thread, not on a new thread.


To start a new thread you create a new instead of the Thread class, give it an object that implements Runnable, and then call the start method on the thread object. When the thread starts, it will call the run method on your object for you.

Another way to start a thread is to subclass Thread and override its run method. Again to start it you must instantiate it and call the start method, not the run method.The reason is the same: if you call run directly it will run the method in the current thread.

See Defining and Starting a Thread for more information about starting new threads in Java.

like image 61
Mark Byers Avatar answered Jan 21 '26 00:01

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!