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