There are in general two ways to create and start a new thread in Java.
1. Extend the Thread class and override the run () method
Public class mythread extends thread {@ override public void run () {// define your task here }}
2. Implement the runnable interface
Public class myrunnable implements runnable {@ override public void run () {// define your task here }}
Then how to start a new thread
For the first way
Mythread thread = new mythread (); thread. Start (); // start will eventually call the run () method of the thread instance
For the second way
Myrunnable runnable = new myrunnable (); New thread (runnable). Start (); // start will eventually call the run () method of the myrunnable instance
In fact, if we check the source of the thread class, it will be something like this
Public class thread implements runnable {private runnable target; Public thread (runnable TAR) {this.tar get = tar;} public void start () {// some magic code which will eventually call run ()} public void run () {if(this.tar get! = NULL) {this.tar get. Run ();}}}
Now we can understand the two ways of creating threads, the first way simply uses Runtime polymorphism, and the second way is even more straightforward.
Note: Please do not directly call thread. run () or runnable. run () If you have CT some parallel execution. as the direct callwill make the code synchronously executed in the current thread, in fact the mythread and myrunnable are simply two classes with nothing
Special. There are some pieces of code in the thread. Start () which can magically create new threads.