Java multi-thread learning and application

Source: Internet
Author: User

Java implements multithreading in two ways:

1. inherit the Thread class and override the run method.

 Package  Com. bjdata. test;  Public   Class Threadtest Extends  Thread {string name = "" ;  Public  Threadtest (string N) {name = N ;}  Public   Void  Run (){ For ( Int I = 0; I <6; I ++ ) {System. Out. println (name + ": Hello:" + I );}}  Public   Static   Void  Main (string [] ARGs) {threadtest test1 = New Threadtest ("" ); Threadtest Test2 = New Threadtest ("B" ); Test1.start (); test2.start ();}} 

Note:ProgramThe start method instead of the run method is called during running.

First running result:

 
A: Hello: 0B: Hello:0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5A: Hello:1A: Hello:2A: Hello:3A: Hello:4A: Hello:5

The second running result:

B: Hello: 0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5A: Hello:0A: Hello:1A: Hello:2A: Hello:3A: Hello:4A: Hello:5

The two running results are inconsistent, indicating that our goal has been achieved

2. Implement runnable

 Package  Com. bjdata. test;  Public   Class Runabletest Implements Runnable {string name = "" ;  Public  Runabletest (string N) {name = N ;}  Public   Void  Run (){  For ( Int I = 0; I <6; I ++ ) {System. Out. println (name + ": Hello:" + I );}}  Public  Static   Void  Main (string [] ARGs) {runabletest test1 = New Runabletest ("" ); Runabletest Test2 = New Runabletest ("B" ); Thread thread1 = New  Thread (test1); thread thread2 = New  Thread (Test2); thread1.start (); thread2.start ();}} 

First running result

A: Hello: 0A: Hello:1A: Hello:2A: Hello:3A: Hello:4A: Hello:5B: Hello:0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5

Second run

A: Hello: 0A: Hello:1A: Hello:2B: Hello:0B: Hello:1B: Hello:2B: Hello:3B: Hello:4B: Hello:5A: Hello:3A: Hello:4A: Hello:5

Note: During running, you must first create a thread object, pass the example that requires multi-thread running, and then call the thread run method.

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.