Java 多線程(四)之守護線程(Daemon)

來源:互聯網
上載者:User

標籤:oid   方法   extend   net   csdn   運行   chm   技術分享   ++   

定義

Java 中有兩種線程: 一種是使用者線程(User Thread),一種是守護線程(Daemon Thread)。

守護線程是一種特殊的線程, 它的特殊有“陪伴”的含義, 當線程中不存在非守護線程時, 則守護線程自動銷毀。

記憶體回收線程就是一種守護線程, 當線程中沒有非守護線程了, 則記憶體回收線程就會自動銷毀。

因此, 守護線程的作用就是為其他非守護線程的線程服務, 當非守護線程不存在時, 其自然就沒有存在的必要了。

如何建立

建立過程與一般的線程一樣, 只需要在建立完之後調用如下函數即可:

setDaemon(true);
判斷
public final boolean isDaemon() {    return daemon;}

可以通過該函數判定一個線程是否為守護線程。

注意事項函數setDaemon(true)必須在 start() 函數之前使用。

如 setDaemon(true) 在 start() 之後, 就會拋異常。如下

也就是說, 線上程運行之後, 其類型(守護與否)就已經確定了, 無法更改。

守護線程中產生的線程也是守護線程;

在 Thread 的 init() 函數中, 可以看到這麼一句:

this.daemon = parent.isDaemon();
測試

建立一個線程類

class PrimeThread extends Thread {    @Override    public void run() {        System.out.println(Thread.currentThread().getName()+" begin");        try {            int i = 0;            while(true) {                Thread.sleep(500);                System.out.println("Current i = " + (i++));            }        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println(Thread.currentThread().getName()+" end");    }}

建立測試方法

public static void main(String[] args) {    PrimeThread primeThread = new PrimeThread();    primeThread.setDaemon(true);    primeThread.start();    try {        Thread.sleep(3000L);        System.out.println("Main 函數準備結束了, 守護線程也機會停止, 不列印");    } catch (InterruptedException e) {        e.printStackTrace();    }}

結果如下:

結果中, Main 函數的線程結束後, primeThread 線程也隨之結束了。

Java 多線程(四)之守護線程(Daemon)

聯繫我們

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