Imagine a scenario where two threads work at the same time, and the main thread, one thread is responsible for initializing the network, one thread is responsible for initializing the resource, and then two threads are executed before the main thread can be executed.
First create a thread that initializes the resource
Public classDatasourcesloaderImplementsRunnable {/*** Main Method of the class*/@Override Public voidrun () {//writes a messsageSystem.out.printf ("Begining data sources loading:%s\n",NewDate ()); //sleeps four seconds Try{TimeUnit.SECONDS.sleep (4); } Catch(interruptedexception e) {e.printstacktrace (); } //writes a messageSystem.out.printf ("Data sources loading has finished:%s\n",NewDate ()); }}View Code
Then create a thread that initializes the network
Public classNetworkconnectionsloaderImplementsRunnable {/*** Main Method of the class*/@Override Public voidrun () {//writes a messageSystem.out.printf ("Begining Network Connections loading:%s\n",NewDate ()); //Sleep Six seconds Try{TimeUnit.SECONDS.sleep (6); } Catch(interruptedexception e) {e.printstacktrace (); } //writes a messageSystem.out.printf ("Network connections loading has finished:%s\n",NewDate ()); }}View Code
Through the TimeUnit.SECONDS.sleep () method; To Hibernate,
And then the main thread executes, through the Join method, when a thread object's join method is called, the calling of his thread will be suspended, knowing this thread to complete these initialization tasks, we call the two thread join method on the main thread, Then the main line routines wait until two threads are executed before execution.
Public classMain {/*** Main method of the class. Create and Star initialization tasks * and wait for their finish *@paramargs*/ Public Static voidMain (string[] args) {//creates and starts a Datasourceloader runnable objectDatasourcesloader Dsloader =NewDatasourcesloader (); Thread Thread1=NewThread (Dsloader, "Datasourcethread"); Thread1.start (); //creates and starts a Networkconnectionsloader runnable objectNetworkconnectionsloader Ncloader =NewNetworkconnectionsloader (); Thread thread2=NewThread (Ncloader, "Networkconnectionloader"); Thread2.start (); //Wait for the finalization of the threads Try{thread1.join (); Thread2.join (); } Catch(interruptedexception e) {e.printstacktrace (); } //Waits a messageSystem.out.printf ("Main:configuration has been loaded:%s\n",NewDate ()); }}
JAVA7 Concurrent Programming Combat (a) waiting for a thread