In some cases, the main thread creates and starts a child thread, if a large number of time-consuming operations are required in a child thread, the main thread will often end before the end of the child thread, and if the main thread wants to wait for the child thread to execute, the Join method is used to obtain a processed data in the child thread. Method Join () is used to wait for the thread object to be destroyed.
public class Test {public
static class Mythread extends Thread {
@Override public
void Run () {
try {
int m = (int) (Math.random () * 10000);
System.out.println ("I will sleep randomly for 0-9 seconds in child threads, time =" +m);
Thread.Sleep (m);
} catch (Interruptedexception e) {
e.printstacktrace ();
}}} public static void Main (string[] args) throws interruptedexception {mythread mythread =new mythread
();
Mythread.start ();
Mythread.join ();
System.out.println ("I'm sure it's done first, but after joining the join, the main main thread waits until the child thread finishes executing");
}
The results are:
I would sleep randomly for 0-9 seconds in a child thread, and the time would be =9566.
Normally I'm going to do it first, but after joining the join, the main main thread waits for the child thread to finish executing
In the main thread, the Mythread.join () is added; Whoever joins the party will wait for someone.
Join also has a join (Millis) method, you can add wait time, the effect of similar sleep, but there is a practical difference.
The bottom of the join is the wait method, so it frees the object lock, while sleep does not release the object lock in the Synchronized method, and the other threads can execute only if the synchronization method is finished.
Working with scenes
Once did a unicom value-added business project, which has a business needs to the unicom side of the leak interface, they call our interface, we conduct business processing, and then return the results, interface requirements are synchronized, real-time return. If the asynchronous can be used to solve the message queue, the whole business logic of the comparison of time is placed in the child thread running, the child thread after running the main thread to return results. It was used in Java as a fence cyclicbarrier, and now it's possible to think of a join.