I stumbled upon a doubt.
I understand the basic difference between start() and run() function in Thread class and Runnable interface.
In below code snippet.
public class ThreadTest extends Thread{
public void run(){
for(int i = 0; i < 3; i++){
System.out.println("-->" + this.getName() + ", "+ i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadTest t1 = new ThreadTest();
t1.setName("firstThread");
ThreadTest t2 = new ThreadTest();
t2.setName("secondThread");
t1.start();
t2.start();
}
}
Output:
-->firstThread, 0
-->secondThread, 0
-->firstThread, 1
-->secondThread, 1
-->firstThread, 2
-->secondThread, 2
If I change t1.start() and t2.start() to t1.run() and t2.run(). I get the below output:
-->firstThread, 0
-->firstThread, 1
-->firstThread, 2
-->secondThread, 0
-->secondThread, 1
-->secondThread, 2
I have 2 doubts here:
- Why there is difference in output in case of
run()andstart()? - It's said that,
start()method creates a new thread and then runs it, whilerun()method just runs the thread. Then what isnewoperator doing here? I suppose,newis creating the thread.
Can someone please clarify.