Use of the Java Join method

Source: Internet
Author: User

In many cases, the main thread creates and starts a child thread, and if a child thread takes a lot of time-consuming operations, the main thread tends to end before the child thread ends. At this point, if the main thread wants to wait for the child thread to finish and then end, such as a child thread processing a data, the main thread to get the value in this data, it is necessary to use the join () method, the function of the method join () is to wait for the thread object to be destroyed.

code example:

 package   com.test;  public  class  Testjoin extends   Thread {@Override  public  void   run () {
    try   { int  secondvalue = (int ) (Math.random () * 10000             catch   (Exception e) {E.printstacktra        CE (); }    }}
 package   com.test;  public  class   Run { public   Static  void   main (string[] args) { /span>try   {testjoin join  = new   Testjoin ();            Join.start ();            Join.join ();                        System.out.println ( "I want to execute the"  catch   (Exception e) {E.printstacktra        CE (); }    }}
Operation Result: 7694 I'm quite done after the thread object executes .

PS: If the Join.join () method in Run.java is commented out, it will print "I want to do it after the thread object has finished executing"

Method Join and Exception:

During the join process, if the current thread object is interrupted, an exception occurs for the current thread.

The parameter in join (long) is the set wait time.

Method Join (long) differs from sleep (long):

The function of method join (long) is implemented internally by using the wait (long) method, so the join (long) method has the feature of releasing a lock. The Thread.Sleep (long) method does not release the lock.

Use of the Java 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.