In both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don’t we directly call the oveerridden run() function? Why always the start function is called to execute a thread?
What happens when a function is called?
When a function is called the following operations take place:
- The arguments are evaluated.
- A new stack frame is pushed into the call stack.
- Parameters are initialized.
- Method body is executed.
- Value is retured and current stack frame is popped from the call stack.
The purpose of start() is to create a separate call stack for the thread. A separate call stack is created by it, and then run() is called by JVM.
Let us see what happens if we don’t call start() and rather call run() directly. We have modified the first program discussed here.
Thread 1 is running Thread 1 is running Thread 1 is running Thread 1 is running Thread 1 is running Thread 1 is running Thread 1 is running Thread 1 is running
We can see from above output that we get same ids for all threads because we have directly called run(). The program that calls start() prints different ids (see this)
This article is contributed by kp93. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Multithreading in Java
- Deadlock in Java Multithreading
- Java Thread Priority in Multithreading
- MatchResult start() method in Java with Examples
- Matcher start(int) method in Java with Examples
- Matcher start() method in Java with Examples
- MatchResult start(int) method in Java with Examples
- Matcher start(String) method in Java with Examples
- Java | How to start learning Java
- Difference between Thread.start() and Thread.run() in Java
- Overriding of Thread class start() method
- Java.util.function.DoublePredicate interface in Java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java.util.function.IntPredicate interface in Java with Examples
- Java.util.function.BiPredicate interface in Java with Examples