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?
The
MyThreadclass is not a thread. It is an ordinary class that implementsRunnableand has a method calledrun.If you call the
runmethod 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
Threadclass, give it an object that implementsRunnable, and then call thestartmethod on the thread object. When the thread starts, it will call therunmethod on your object for you.Another way to start a thread is to subclass
Threadand override itsrunmethod. Again to start it you must instantiate it and call thestartmethod, not therunmethod.The reason is the same: if you callrundirectly it will run the method in the current thread.See Defining and Starting a Thread for more information about starting new threads in Java.