Java multithreaded Programming (i)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.