JAVA守護線程與使用者線程的區別

來源:互聯網
上載者:User

標籤:java   線程   

public class DaemonTest {    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) ;   // When false, (i.e. when it's a user thread),                // the Worker thread continues to run.                // When true, (i.e. when it's a daemon thread),                // the Worker thread terminates when the main                 // thread terminates.    }    public void run() {        int count=0 ;        while (true) {            System.out.println("Hello from Worker "+count++) ;            try {                sleep(5000);            } catch (InterruptedException e) {}        }    }}

簡單理解:守護進程是不會阻止JVM的關閉的。當有使用者線程運行時,JVM不能關閉。當沒有使用者線程運行時,有沒有守護線程沒關係,JVM都會關閉。

守護線程應用樣本:java garbage collection。當沒有線程運行時,不會產生垃圾,garbage collection也就沒有發揮作用,JVM可以關閉。

守護線程應用背景:後台線程(比如可以收集某些系統狀態的線程,發送email的線程,等不希望影響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.