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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With