1, Java to create multithreading method one: (1) Implement the Runnable interface and implement the run () method, (2) Submit the Runable object to a thread constructor, call the start () method.
"Program instance" single thread
1 Public classLiftOffImplementsRunnable {2 3 protected intCountdown = 10;4 5 Private Static intTaskcount = 0;6 7 Private Final intid = taskcount++;8 9 PublicLiftOff () {Ten } One A PublicLIFTOFF (intCountdown) { - This. Countdown =Countdown; - } the - PublicString status () { - return"#" + ID + "(" + (Countdown > 0?) Countdown: "liftoff!") + "),"; - } + - @Override + Public voidrun () { A while(countdown--> 0) { at System.out.print (status ()); - Thread.yield (); - } - } - -}
1 Public classMain {2 3 Public Static voidMain (string[] args) {4Thread thread =NewThread (NewLiftOff ());5 Thread.Start ();6System.out.println ("Waiting for LiftOff");7 }8 9}
"Run Results"
"Results Analysis"
In the main function, the main thread (main threads) creates only one thread, and you can see that the output is ordered and controllable. In addition, you can see that the main thread does not wait for the created thread.
"Program Instance 2" multithreading
1 Public classMain {2 3 Public Static voidMain (string[] args) {4 for(inti = 0; I < 5; i++)5 NewThread (NewLiftOff ()). Start ();6System.out.println ("Waiting for LiftOff");7 }8 9}
"Run Results"
"Results Analysis"
The main thread now creates and executes 5 threads, each running independently of each other, and the output is not controllable.
Java multithreaded Programming (i)