I. Overview
The join () method allows one thread to wait for another thread to end and the join () method to be disruptive, that is, at a certain point in time, the thread can no longer wait for execution to continue.
Let's take a look at this example first.
Public Static voidMain (string[] args) throws interruptedexception {Thread T=NewThread ((){intstream.rangeclosed (1, -). ForEach ((e)-{System. out. println (Thread.CurrentThread (). GetName () +"-- "+e); } ); }) ; T.start (); T.join (); System. out. println ("main thread is runnging ..."); }
We found that the result of execution showed that the main thread was executed when the child thread was fully executed.
With this example, we can see that the main thread will wait until the child thread is fully executed.
Two. Use join () to complete task distribution and collection
Private Staticlist<string> result =NULL; Static{result=NewArraylist<>(); Collections.synchronizedcollection (result); } Public Static voidMain (string[] args) throws interruptedexception {Thread T1= GetThread (1); Thread T2= GetThread (2); T1.start (); T2.start (); T1.join (); T2.join (); Result.stream (). ForEach (System. out::p rintln); } Private StaticThread GetThread (Longseconds) { return NewThread (() { Try{TimeUnit.SECONDS.sleep (SECONDS); } Catch(interruptedexception e) {e.printstacktrace (); } String threadname=Thread.CurrentThread (). GetName (); Result.add (ThreadName); System. out. println (ThreadName +"We 're done with the mission."); }); }
In the above example, we first common two threads are subtasks, the results are collected into a container.
When the sub-thread completes the task, our main thread continues to execute, and now results in the result container.
Then, the main thread can complete its own task collection work through the child results.
005 Thread's Join method