In some cases, we have to wait for the thread to terminate. For example, our program must initialize some of the necessary resources before performing other tasks. You can use threads to complete these initialization tasks, wait for the thread to terminate, and then perform other tasks for the program.
For this purpose, we use the Join () method of the thread class. When a thread object's join () method is called, the thread that invokes it is suspended until the thread object finishes its task.
package concurrency;import java.util.date;import java.util.concurrent.timeunit;public Class datasourcesloader implements runnable { private int second; public datasourcesloader (Int second) { this.second = second; } @ Override public void run () { system.out.printf ("beginning data sources loading: %s\n", new Date ()); try { timeunit.seconds.sleep (second); } catch (interruptedexception e) { e.printstacktrace (); &Nbsp; } system.out.printf (" Data sources loading has finished: %s\n ", new date ()); } public static void main (String[] args) { DataSourcesLoader dsLoader = new Datasourcesloader (4); thread thread1 = new Thread (Dsloader, "DataSourceThread1"); datasourcesloader Dsloader2 = new datasourcesloader (6); thread thread2 = new thread (DsLoader2, "DataSourceThread2"); thread1.start (); thread2.start (); try { thread1.join (); thread2.join (); } catch (interruptedexception e) { e.printstacktrace (); } system.out.printf ("main: configuration has been Loaded: %s\n ", new date ()); }}
When the THREAD1 thread finishes running and the thread2 thread ends, the main thread object will continue to run and print out the final information.
Java provides two different forms of join () methods:
When a thread calls the join () method of another thread, if it is using the first join (), it does not have to wait for the called thread to terminate, and it will continue to run if the millisecond clock specified by the parameter has arrived. For example, with this code threadb.join (Threada), Threada will hang until one of the following two conditions is met:
When any one of the two conditions is true, the join () method returns. The second join () method is similar to the first, except that it accepts two parameters of milliseconds and nanoseconds.
Waiting for the thread to terminate