Java7並發編程實戰(一) 線程的等待

來源:互聯網
上載者:User

標籤:

試想一個情景,有兩個線程同時工作,還有主線程,一個線程負責初始化網路,一個線程負責初始化資源,然後需要兩個線程都執行完畢後,才能執行主線程

  首先建立一個初始化資源的線程

  

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並發編程實戰(一) 線程的等待

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.