The start () method is called on the tread object of the thread instead of run () or another method.
Before invoking the Start method, the thread is in the new state and the new State refers to having a thread object! But there is not a real thread.
A series of complex things happened after the call to start
Start a new execution thread (with a new call stack)
The thread is transferred from the new state to the operational state
When the thread obtains an opportunity to execute, its target run () method runs
In Java to implement multi-threading, there are two ways, one is to continue the thread class, and the other is to implement the Runable interface.
For classes that directly inherit the thread, the code's approximate framework is:
class class Name extends thread{Method 1; Method 2; .... Public void run () {// other code ... } property 1; property 2; ...}
classHello extends Thread { Publichello () {} PublicHello (String name) { This. Name =name; } Public voidrun () { for(inti =0; I <5; i++) {System. out. println (name +"Run"+i); } } Public Static voidMain (string[] args) {Hello H1=NewHello"A"); Hello H2=NewHello"B"); H1.start (); H2.start (); } PrivateString name;}
The running of the thread requires the support of the local operating system. So you need to use Start () instead of directly using Run ().
by implementing Runnable Interface:
class class Name implements runnable{Method 1; Method 2; .... Public void run () {// other code ... } property 1; property 2; ...}
classHello implements Runnable { Publichello () {} PublicHello (String name) { This. Name =name; } Public voidrun () { for(inti =0; I <5; i++) {System. out. println (name +"Run"+i); } } Public Static voidMain (string[] args) {Hello H1=NewHello"Thread A"); Thread Demo=NewThread (H1); Hello H2=NewHello"thread B"); Thread Demo1=NewThread (H2); Demo.start (); Demo1.start (); } PrivateString name;}
"Possible run Results":
Thread A runs 0
Thread B runs 0
Thread B runs 1
Thread B runs 2
Thread B runs 3
Thread B runs 4
Thread A runs 1
Thread A runs 2
Thread A runs 3
Thread A runs 4
Try to implement the Runnable interface
Ways to start a thread