Basic Overview of Java Multithreading (vii)--join () method

Source: Internet
Author: User

In many cases, the main thread creates and starts a child thread, and if there are a lot of time-consuming operations in the child thread, the main thread will end earlier than the child thread, and if you want the main thread to wait for the child thread to end, then we can use the join () method. The call to the join () method means that the current thread makes the thread that called the method execute and then executes itself. The API documentation is as follows:

 Public Final voidJoinLongMillis,intNanos)throwsInterruptedexceptionwaits at the most millis milliseconds plus Nanos nanoseconds for  Thisthread to die. This implementation uses a loop of This. Wait calls conditioned on This. isAlive. As a thread terminates the This. Notifyall method is invoked. It is recommended this applications not use wait, notify, or Notifyall on Thread instances. Parameters:millis-The time to wait in Millisecondsnanos-0-999999additional nanoseconds to Waitthrows:illegalargumentexception-ifThe value of Millis is negative, or the value of Nanos was not in the range 0-999999interruptedexception-ifAny thread have interrupted the current thread. The interrupted status of the current thread was cleared when ThisException is thrown

The simple translation is as follows: The thread that called the method waits for the Millils+nanos time until the thread finishes executing (the Thread.isalive () method that calls the method returns false). The implementation of this method is to use a loop to determine the thread IsAlive () method, and if true, then call the Wait () method to await. When the thread ends, the Notifyall () method is called. If you call join () and then call Notify ()/notifyall (), the Join () method may fail. The source code is as follows:

 Public Final synchronized voidJoinLongMillis)throwsinterruptedexception {LongBase =System.currenttimemillis (); Longnow = 0; if(Millis < 0) {            Throw NewIllegalArgumentException ("Timeout value is negative"); }        if(Millis = = 0) {             while(IsAlive ()) {Wait (0); }        } Else {             while(IsAlive ()) {LongDelay = Millis-Now ; if(Delay <= 0) {                     Break;                } wait (delay); now= System.currenttimemillis ()-Base; }        }    }

Example:

 PackageSoarhu;classservice{voidReadmethod () {Try {             for(inti = 0; I < 5; i++) {System.out.println (i); }        }Catch(Exception e) {e.printstacktrace (); }    }} Public classTest { Public Static voidMain (string[] args)throwsException {Service o=NewService (); NewThread () {@Override Public voidrun () {O.readmethod ();        }}.start (); System.out.println ("Main ..."); }}

Output Result:

main ... .. 012340

Results analysis: The main thread method is executed first. If you want the child thread to finish first, then the main thread is executed. Then you can call the join () method.

 PackageSoarhu;classservice{voidReadmethod () {Try {             for(inti = 0; I < 25; i++) {Thread.yield (); System.out.println (i+" "+Thread.CurrentThread (). GetName ()); }        }Catch(Exception e) {e.printstacktrace (); }    }} Public classTest { Public Static voidMain (string[] args)throwsException {Service o=NewService (); Thread T=NewThread () {@Override Public voidrun () {O.readmethod ();           }            };           T.start ();        T.join ();  for(inti = 0; I < 10; i++) {System.out.println ("Main ..." +i); }    }}

Output Result:

0 Thread-01 Thread-02 Thread-03 Thread-04 Thread-05 Thread-06 Thread-07 Thread-08 Thread-09 Thread-010 Thread-011 Thread-0 Thread-013 Thread-014 Thread-015 Thread-016 Thread-017 Thread-018 Thread-019 Thread-020 Thread-021 Thread-022 Thread-0 Thread-024 Thread-0main ... . 0main ... . 1main ... . 2main ... . 3main ... . 4main ... . 5main ... . 6main ... . 7main ... . 8main ... . 90

It is true that the main thread is not executed until the child thread has finished executing. We do not need to join () can also refer to the API source code to implement join (). as follows:

 Public classTest { Public Static voidMain (string[] args)throwsException {Service o=NewService (); Thread T=NewThread () {@Override Public voidrun () {O.readmethod ();        }        };        T.start (); //T.join ();        synchronized(t) { Do{t.wait (); }  while(T.isalive ()); }         for(inti = 0; I < 10; i++) {Thread.yield (); System.out.println ("Main ..." +i); }    }}

Output Result:

0 Thread-01 Thread-02 Thread-03 Thread-04 Thread-05 Thread-06 Thread-07 Thread-08 Thread-09 Thread-010 Thread-011 Thread-0 Thread-013 Thread-014 Thread-015 Thread-016 Thread-017 Thread-018 Thread-019 Thread-020 Thread-021 Thread-022 Thread-0 Thread-024 Thread-0main ... . 0main ... . 1main ... . 2main ... . 3main ... . 4main ... . 5main ... . 6main ... . 7main ... . 8main ... . 90

The visible join () method is implemented simply by adding a synchronous method, and then the internal loop determines whether the thread ends, and if it is not, then Jon () is consistently blocked, causing the following code to not be executed, if the wait () of the thread is called after the join () method is called Method, a deadlock can occur, and a deadlock or join () failure may occur when calling notify (). Examples are as follows:

 PackageSoarhu;ImportJava.util.concurrent.TimeUnit;classService {voidReadmethod () {Try {             for(inti = 0; I < 25; i++) {TimeUnit.MILLISECONDS.sleep (300);                Thread.yield ();  while(i==5) {//1 Line                   synchronized( This){                       //wait (); //deadlock occurs                        This. Notifyall (); }} System.out.println (I+ " " +Thread.CurrentThread (). GetName ()); }        } Catch(Exception e) {e.printstacktrace (); }    }} Public classTest { Public Static voidMain (string[] args) {Service o=NewService (); Thread T=NewThread () {@Override Public voidrun () {O.readmethod ();        }        };        T.start (); Try{t.join ();  for(inti = 0; I < 10; i++) {System.out.println ("Main ..." +i); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Output Result: Deadlock

0 Thread-01 Thread-02 Thread-03 Thread-04 Thread-0

Because the wait () method is used internally by join (), a break exception can also be thrown, for example:

 PackageSoarhu;ImportJava.util.concurrent.TimeUnit;classServiceextendsThread {@Override Public voidrun () {Try {             for(inti = 0; I < 25; i++) {TimeUnit.MILLISECONDS.sleep (300);                Thread.yield (); if(i==5){                    This. Interrupt (); } System.out.println (I+ " " +Thread.CurrentThread (). GetName ()); }        } Catch(Exception e) {e.printstacktrace (); }    }} Public classTest { Public Static voidMain (string[] args) {Service o=NewService ();        O.start (); Try{o.join (); System.out.println ("IsAlive?" +o.isalive ());  for(inti = 0; I < 10; i++) {System.out.println ("Main ..." +i); }        } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Output Result:

0 Thread-01 Thread-02 Thread-03 Thread-04 Thread-0Java.lang.InterruptedException:sleep interrupted at Java.lang.Thread.sleep (Native Method) at Java.lang.thread.s Leep (Thread.java:340)5 Thread-0At java.util.concurrent.TimeUnit.sleep (Timeunit.java:386) isAlive?falseAt Soarhu. Service.run (Test.java:12) Main ... ..0main ... ..1main ... ..2main ... ..3main ... ..4main ... ..5main ... ..6main ... ..7main ... ..8main ... ..9Process finished with exit code0

Basic Overview of Java Multithreading (vii)--join () method

Related Article

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.