Java Multi-threaded join ()

Source: Internet
Author: User

Suppose the main line thread another THREAD1 thread after the call to Thread1.start ():

If Thread1.join () is called on the main line thread, then the main thread will block until the main thread continues execution until Thread1 is finished.

If Thread1.join () is not called in the main thread, then the main thread and the THREAD1 thread are executed in parallel.

The test code is as follows:

1  Public classJointhreadextendsthread{2      PublicJointhread (String name) {3           Super(name);4     }5     6      Public voidrun () {7            for(inti=0; i<10; i++){8                  for(Longk=0; k<100000000; k++){9System.out.println ( This. GetName () + ":" +i);Ten                 }  One           } A     } -      -      Public Static voidMain (string[] args) { theThread Thread1 =NewJointhread ("AA AA"); - Thread1.start (); -           Try{ -Thread1.join ();//join IS here ~ +}Catch(interruptedexception e) { - e.printstacktrace (); +           } A            for(inti=0; i<10; i++){ at                for(Longk=0; k<100000000; k++){ -System.out.println (Thread.CurrentThread (). GetName () + ":" +i); -               }    -           } -System.out.println ("Over"); -     } in}

The above code executes the following results:

AA aa:0
AA aa:0
AA aa:0
AA aa:0
AA aa:0
AA aa:0

This is because the main thread waits for Thread1 to execute, so thread1 prints a bunch of AA aa:0

If the 17th to 21st Line is commented out and then run, the result is as follows:

main:0

AA aa:0

AA aa:0

AA aa:0
main:0
main:0

This is because the main thread and the THREAD1 thread are running concurrently.

Java Multi-threaded join ()

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.