Java中的守護線程

來源:互聯網
上載者:User

標籤:

Java中的守護線程

Java中的守護線程與UNIX中的守護線程概念不同,UNIX中的守護線程相當於一項服務,一直運行在後台,而Java中的守護線程是這樣定義的:

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running.

也就是說,當程式中只有守護線程時,JVM就會自動結束,典型的守護線程就是記憶體回收行程(GC)。

當我們建立一個新的線程時,它會繼承其父線程的守護線程的狀態,就是說其父線程如果是守護線程,其子線程也是守護線程。

守護線程與一般線程的區別是:一般線程如果還沒有執行完畢,JVM不會退出,而守護線程不一樣,當一般線程全部執行完畢,而守護線程還沒有執行完畢,JVM會捨棄執行剩下的守護線程,直接退出虛擬機器,因此,與I/O相關的操作不能交給守護線程去操作。

下面看一個例子:

package com.test;/** * Created by z1178 on 2015-08-09. */public class MyTest {    public static void main(String[] args) {        new WorkerThread().start();        try {            Thread.sleep(7500);        } catch (InterruptedException e) {            System.out.println("main thread ending");        }    }}class WorkerThread extends Thread{    public WorkerThread() {        setDaemon(true);    }    public void run(){        int count=0;        while(true){            System.out.println("Hello from Worker "+count++);            try {                sleep(5000);            } catch (Exception e) {                e.printStackTrace();            }        }    }}

如果我們將setDaemon設為true或false,會等到不同的結果,如果為true,其結果如下:

Hello from Worker 0
Hello from Worker 1

說明當主線程執行完畢,JVM就退出了,如果setDaemon設為false,其會一直執行下去,JVM不會退出。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java中的守護線程

聯繫我們

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