《多線程編程》學習之二:Thread.currentThread()、isAlive()、Thread.sleep()的使用

來源:互聯網
上載者:User

1、Thread.currentThread()方法: 返回當前正在啟動並執行線程

一個簡單的例子:

     

        MyThread_7.java類的建構函式是被main線程調用的,而run()方法是被名為Thread-0的線程調用的。注意這裡使用thread.start(),而不是thread.run(),前者run()方法是自動調用的,後者並沒有另起一個線程,而是直接調用MyThread_7類的run()方法。


2、isAlive()方法:判斷當前線程是否處於活動狀態

       “活動狀態”是指線程處於運行或者準備開始啟動並執行狀態。下面通過兩個例子說明this與Thread.currentThread()的差異。

(1)例子一:



        分析:Thread.currentThread()返回的是當前啟動並執行線程,而this是指當前對象。本例中,MyThread_8.java的構造方法是被main線程調用的,run()方法是被線程Thread-0調用的,而this是指MyThread_8類的執行個體,是線程Thread-0。因此在調用構造方法時,Thread.currentThread().getName()返回的是main,this.getName()返回的是Thread-0,而由於當前啟動並執行線程是main,而不是this對應的Thread-0線程,故this.isAlive()返回false。在調用run()方法時的分析可以類比。


(2)例子二:將線程對象以構造參數的方式傳遞給Thread對象,將run()方法交由其它線程來調用



      分析:與上一個例子對比,發現run()的輸出不同。本例中,this(對應Thread-0)的run方法是交由線程Thread-run執行的,而不是由自己執行。所以在run()方法執行時,Thread.currentThread().getName()返回的是Thread-run,this.isAlive()返回的是false。

          要分清楚Thread.currentThread()與this的區別。


3、Thread.sleep():使“正在執行的線程”休眠指定的毫秒數。

        這個“正在執行的程式”是指this.currentThread()返回的線程。


          在run()方法中調用Thread.sleep(2000)方法,會使正在啟動並執行線程(Thread-0)休眠2000毫秒,是run()輸出的begin time與end time之差。由本例還可見,mian線程與Thread-0線程是非同步執行的,main線程運行完後,Thread-0線程再運行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.