Java 線程類別


Java 線程類別

守護線程和非守護線程

守護線程和非守護線程之前的唯一區別在於:是否阻止JVM的正常退出。

JVM正常退出是與異常退出相對的概念,異常退出如調用System.exit(status)退出JVM進程,調用Linux的kill命令殺死進程等。

JVM正常退出的條件是JVM中所有非守護線程結束任務,即使還有守護線程在運行。

可以通過setDaemon方法設置線程的屬性。

父進程與子進程

子進程是由父進程創建並啟動的,在Java中兩者沒有本質區別。JVM在啟動時,首先創建main線程,去執行main方法。在main方法中創建其他的線程后,如果main線程執行完畢,其他線程也會繼續執行。

需要注意的是,子線程會在默認情況下繼承父線程的類別,如果父線程是守護線程,子線程也是守護線程。當然可以通過setDaemon方法改變屬性。

JVM的退出

通過調用System.exit(status)方法會直接退出JVM進程,但是退出線程前會做一些工作。

  1. 會自動的檢測注冊的hook 線程,並調用其run方法。
  2. 釋放資源,關閉JVM。
package com.wz.thread;

public class Exit
{
    public static void main(String[] args)
    {
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run()
            {
                System.out.println("hook thread start");
                try
                {
                    Thread.sleep(1000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                System.out.println("hook thread end");
            }
        });

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    System.out.println("worker thread");
                    try
                    {
                        Thread.sleep(100);
                    } catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        try{
            System.out.println("start main");
            System.exit(0);
        }finally
        {
            System.out.println("the finally block");
        }
    }
}

上述的程序執行結果如下:

start main
worker thread
hook thread start
worker thread
worker thread
worker thread
worker thread
worker thread
worker thread
worker thread
worker thread
worker thread
hook thread end

可以看出,在執行了System.exit(0)后會立即終止當前線程的執行,並啟動hook線程,其他線程正常的執行直到hook線程執行完畢。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM