005 Thread's Join method

Source: Internet
Author: User

I. Overview

The join () method allows one thread to wait for another thread to end and the join () method to be disruptive, that is, at a certain point in time, the thread can no longer wait for execution to continue.

Let's take a look at this example first.

     Public Static voidMain (string[] args) throws interruptedexception {Thread T=NewThread ((){intstream.rangeclosed (1, -). ForEach ((e)-{System. out. println (Thread.CurrentThread (). GetName () +"-- "+e);        } );                })  ;        T.start ();        T.join (); System. out. println ("main thread is runnging ..."); }

We found that the result of execution showed that the main thread was executed when the child thread was fully executed.

With this example, we can see that the main thread will wait until the child thread is fully executed.

Two. Use join () to complete task distribution and collection

Private Staticlist<string> result =NULL; Static{result=NewArraylist<>();    Collections.synchronizedcollection (result); }         Public Static voidMain (string[] args) throws interruptedexception {Thread T1= GetThread (1); Thread T2= GetThread (2);        T1.start ();        T2.start ();        T1.join ();                T2.join (); Result.stream (). ForEach (System. out::p rintln); }        Private StaticThread GetThread (Longseconds) {        return NewThread (() {            Try{TimeUnit.SECONDS.sleep (SECONDS); } Catch(interruptedexception e) {e.printstacktrace (); } String threadname=Thread.CurrentThread (). GetName ();            Result.add (ThreadName); System. out. println (ThreadName +"We 're done with the mission.");    }); }

In the above example, we first common two threads are subtasks, the results are collected into a container.

When the sub-thread completes the task, our main thread continues to execute, and now results in the result container.

Then, the main thread can complete its own task collection work through the child results.

005 Thread's Join 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.