標籤:
試想一個情景,有兩個線程同時工作,還有主線程,一個線程負責初始化網路,一個線程負責初始化資源,然後需要兩個線程都執行完畢後,才能執行主線程
首先建立一個初始化資源的線程
public class DataSourcesLoader implements Runnable { /** * Main method of the class */ @Override public void run() { // Writes a messsage System.out.printf("Begining data sources loading: %s\n",new Date()); // Sleeps four seconds try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } // Writes a message System.out.printf("Data sources loading has finished: %s\n",new Date()); }}View Code
然後建立一個初始化網路的線程
public class NetworkConnectionsLoader implements Runnable { /** * Main method of the class */ @Override public void run() { // Writes a message System.out.printf("Begining network connections loading: %s\n",new Date()); // Sleep six seconds try { TimeUnit.SECONDS.sleep(6); } catch (InterruptedException e) { e.printStackTrace(); } // Writes a message System.out.printf("Network connections loading has finished: %s\n",new Date()); }}View Code
通過TimeUnit.SECONDS.sleep()方法; 進行休眠,
然後主線程執行,通過join方法,當一個線程對象的join方法被調用時,調用他的線程將會被掛起,知道這個線程來完成這些初始化任務,我們在主線程分別調用兩個Thread的join方法,那麼主線程會等到兩個線程都執行完畢才會執行下去。
public class Main { /** * Main method of the class. Create and star two initialization tasks * and wait for their finish * @param args */ public static void main(String[] args) { // Creates and starts a DataSourceLoader runnable object DataSourcesLoader dsLoader = new DataSourcesLoader(); Thread thread1 = new Thread(dsLoader,"DataSourceThread"); thread1.start(); // Creates and starts a NetworkConnectionsLoader runnable object NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader(); Thread thread2 = new Thread(ncLoader,"NetworkConnectionLoader"); thread2.start(); // Wait for the finalization of the two threads try { thread1.join(); thread2.join(); } catch (InterruptedException e) { e.printStackTrace(); } // Waits a message System.out.printf("Main: Configuration has been loaded: %s\n",new Date()); }}
Java7並發編程實戰(一) 線程的等待