I. Overview
We often want a thread to wait for another thread to complete before running. At this time, we can use the join() method to complete this function.
The meaning of the join() method is to complete a thread and wait for another thread to finish running.
2. Test of join() method
Thread thread = new Thread(new Runnable() { @Override public void run() { for (int x = 0; x < 10; x++) { System.out.println("thread is running..."); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace (); } } } }); thread.start(); thread.join(); System.out.println("main thread is ended");
Running the above code, we can find that the main thread will not run until the child thread has finished running.
3. Summary
The join() method itself is a more useful method, but since version 5 provides more powerful order aids, we now use the join() method less often.