JAVA DAEMON線程的理解

來源:互聯網
上載者:User

標籤:catch   read   cep   down   gpo   mon   rac   try   0ms   

java線程分兩種:使用者線程和daemon線程。daemon線程或進程就是守護線程或者進程,但是java中所說的daemon線程和linux中的daemon是有一點區別的。

linux中的daemon進程實際是指運行在後台提供某種服務的進程,例如cron服務的crond、提供http服務的httpd;而java中的daemon線程是指jvm執行個體中只剩下daemon的時候,jvm就會退出。

我們通過以下實驗來看下daemon線程和普通使用者線程的區別

  1. 建立一個運行死迴圈的daemon線程,主線程運行5s後退出,daemon線程也會退出。
public static void main(String[] args) throws InterruptedException {        Thread thread = new Thread(new MyThread());        thread.setDaemon(true); // 設定線程為daemon線程        thread.start();        Thread.sleep(5000); // 5s後主線程退出    }    static class MyThread implements Runnable {        @Override        public void run() {            while (true) { // 線程死迴圈                try {                    // 100ms 列印一次hello                    Thread.sleep(100);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("hello");            }        }    }

運行結果:5ms daemon線程退出。

hellohellohellohellohellohellohellohellohellohellohelloProcess finished with exit code 0
  1. 注釋掉daemon,使得線程成為一個普通的使用者線程

    public static void main(String[] args) throws InterruptedException {    Thread thread = new Thread(new MyThread());    // thread.setDaemon(true); // 普通的使用者線程    thread.start();    Thread.sleep(5000); // 5s後主線程退出}static class MyThread implements Runnable {    @Override    public void run() {        while (true) { // 線程死迴圈            try {                // 100ms 列印一次hello                Thread.sleep(100);            } catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("hello");        }    }}

    運行結果:線程在主線程運行完後不會退出,一直死迴圈

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.