Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between running and starting a thread [duplicate]

i don't understand the difference between starting and running a thread, i tested the both methods and they outputs the same result, first i used a combination of run() and start on the same thread and they did the same function as follows:

public class TestRunAndStart implements Runnable {
public void run() {
    System.out.println("running");
}
public static void main(String[] args) {
     Thread t = new Thread(new TestRunAndStart());
     t.run();
     t.run();
     t.start(); 
}

}

the output is:

running
running
running

then i saw the javadoc of the run() method said that: If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns so i tried to use the run() method without a separate runnable as follows :

public class TestRun extends Thread {
public void run(){
    System.out.println("Running Normal Thread");
}
public static void main(String[]args){
    TestRun TR=new TestRun();
    TR.run();
   }

}

and it also executes the run() method and prints Running Normal Thread although it's constructed without a separate runnable! so what's the main difference between the two methods

like image 356
Eslam Mohamed Mohamed Avatar asked Apr 05 '13 18:04

Eslam Mohamed Mohamed


2 Answers

Thread.run() does not spawn a new thread whereas Thread.start() does, i.e Thread.run actually runs on the same thread as that of the caller whereas Thread.start() creates a new thread on which the task is run.

like image 140
Extreme Coders Avatar answered Oct 05 '22 22:10

Extreme Coders


When you call run, you're just executing the run method in the current thread. You code thus won't be multi-threaded.

If you call start, this will start a new thread and the run method will be executed on this new thread.

like image 31
Denys Séguret Avatar answered Oct 05 '22 22:10

Denys Séguret