This is part of the notes from an online course (Java Multithreading) I’m taking on Udemy. Nothing complicated.
There are normally three ways to create threads (Examples on gist):
- Create a class that extends the Thread class
- Create a class that implements the Runnable interface
- Create a Thread anonymously
Whichever we choose to use, we must override or implement the public void run method.
All Java programs have a main thread, but we can create and invoke other threads from the main thread.
To do that, we need to call the start() method of each thread we want to invoke from main thread. It will look for the run() method and run that in its own special thread, not in the main thread (refer to the App.java in the gist).
The start() method will return immediately so the main thread will continue its execution of the next line of code.
However, if we accidentally call the run() method of those threads, then the method run() will be executed in the main thread, not in its own special thread! So be careful.