1. 程式人生 > >Java 守護線程概述

Java 守護線程概述

ive cnblogs 必須 daemon cat adg 程序 優先 util

原文出處: 朱小廝


Java的線程分為兩種:User Thread(用戶線程)、DaemonThread(守護線程)。

只要當前JVM實例中尚存任何一個非守護線程沒有結束,守護線程就全部工作;只有當最後一個非守護線程結束是,守護線程隨著JVM一同結束工作,Daemon作用是為其他線程提供便利服務,守護線程最典型的應用就是GC(垃圾回收器),他就是一個很稱職的守護者。

User和Daemon兩者幾乎沒有區別,唯一的不同之處就在於虛擬機的離開:如果 User Thread已經全部退出運行了,只剩下Daemon Thread存在了,虛擬機也就退出了。 因為沒有了被守護者,Daemon也就沒有工作可做了,也就沒有繼續運行程序的必要了。

首先看一個例子,主線程中建立一個守護線程,當主線程結束時,守護線程也跟著結束。

package
com.daemon; import java.util.concurrent.TimeUnit; public class DaemonThreadTest { public static void main(String[] args) { Thread mainThread = new Thread(new Runnable(){ @Override public void run() { Thread childThread = new Thread(new
ClildThread()); childThread.setDaemon(true); childThread.start(); System.out.println("I‘m main thread..."); } }); mainThread.start(); } } class ClildThread implements Runnable { @Override public void run() { while
(true) { System.out.println("I‘m child thread.."); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }

運行結果:

I‘m child thread..

I‘m main thread...

如果不何止childThread為守護線程,當主線程結束時,childThread還在繼續運行,如下:

package com.daemon;

import java.util.concurrent.TimeUnit;

public class DaemonThreadTest
{
    public static void main(String[] args)
    {
        Thread mainThread = new Thread(new Runnable(){
            @Override
            public void run()
            {
                Thread childThread = new Thread(new ClildThread());
                childThread.setDaemon(false);
                childThread.start();
                System.out.println("I‘m main thread...");
            }
        });
        mainThread.start();
    }
}

class ClildThread implements Runnable
{
    @Override
    public void run()
    {
        while(true)
        {
            System.out.println("I‘m child thread..");
            try
            {
                TimeUnit.MILLISECONDS.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

運行結果:

I‘m main thread...
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..(無限輸出)

可以看到,當主線程結束時,childThread是非守護線程,就會無限的執行。

守護線程有一個應用場景,就是當主線程結束時,結束其余的子線程(守護線程)自動關閉,就免去了還要繼續關閉子線程的麻煩。不過博主推薦,如果真有這種場景,還是用中斷的方式實現比較合理。

還有補充一點,不是說當子線程是守護線程,主線程結束,子線程就跟著結束,這裏的前提條件是:當前jvm應用實例中沒有用戶線程繼續執行,如果有其他用戶線程繼續執行,那麽後臺線程不會中斷,如下:

package com.daemon;

import java.util.concurrent.TimeUnit;

public class DaemonThreadTest
{
    public static void main(String[] args)
    {
        Thread mainThread = new Thread(new Runnable(){
            @Override
            public void run()
            {
                Thread childThread = new Thread(new ClildThread());
                childThread.setDaemon(true);
                childThread.start();
                System.out.println("I‘m main thread...");
            }
        });
        mainThread.start();

        Thread otherThread = new Thread(new Runnable(){
            @Override
            public void run()
            {
                while(true)
                {
                    System.out.println("I‘m other user thread...");
                    try
                    {
                        TimeUnit.MILLISECONDS.sleep(1000);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        });
        otherThread.start();
    }
}

class ClildThread implements Runnable
{
    @Override
    public void run()
    {
        while(true)
        {
            System.out.println("I‘m child thread..");
            try
            {
                TimeUnit.MILLISECONDS.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

運行結果:

I‘m other user thread...
I‘m child thread..
I‘m main thread...
I‘m other user thread...
I‘m child thread..
I‘m other user thread...
I‘m child thread..
I‘m child thread..
I‘m other user thread...
I‘m other user thread...
I‘m child thread..
I‘m child thread..
I‘m other user thread...
I‘m other user thread...
I‘m child thread..
I‘m other user thread...
I‘m child thread..
I‘m other user thread...
I‘m child thread..
I‘m other user thread...
I‘m child thread..
I‘m other user thread...
I‘m child thread..
I‘m other user thread...
I‘m child thread..
I‘m other user thread...
I‘m child thread..(無限輸出)

如果需要在主線程結束時,將子線程結束掉,可以采用如下的中斷方式:

package com.self;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadTest
{

    public static void main(String[] args)
    {
        Thread mainThread = new Thread(new Runnable(){
            public void run()
            {
                System.out.println("主線程開始...");
                Thread sonThread = new Thread(new Thread1(Thread.currentThread()));
                sonThread.setDaemon(false);
                sonThread.start();

                try
                {
                    TimeUnit.MILLISECONDS.sleep(10000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                System.out.println("主線程結束");
            }
        });
        mainThread.start();
    }

}

class Thread1 implements Runnable
{
    private Thread mainThread;

    public Thread1(Thread mainThread)
    {
        this.mainThread = mainThread;
    }

    @Override
    public void run()
    {
        while(mainThread.isAlive())
        {
            System.out.println("子線程運行中....");
            try
            {
                TimeUnit.MILLISECONDS.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

}

運行結果:

主線程開始...
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
子線程運行中....
主線程結束

主線程結束

回歸正題,這裏有幾點需要註意:
(1) thread.setDaemon(true)必須在thread.start()之前設置,否則會跑出一個IllegalThreadStateException異常。你不能把正在運行的常規線程設置為守護線程。
(2) 在Daemon線程中產生的新線程也是Daemon的。
(3) 不要認為所有的應用都可以分配給Daemon來進行服務,比如讀寫操作或者計算邏輯。
寫java多線程程序時,一般比較喜歡用java自帶的多線程框架,比如ExecutorService,但是java的線程池會將守護線程轉換為用戶線程,所以如果要使用後臺線程就不能用java的線程池。
如下,線程池中將daemon線程轉換為用戶線程的程序片段:

static class DefaultThreadFactory implements ThreadFactory {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    DefaultThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                              Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" +
                      poolNumber.getAndIncrement() +
                     "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r,
                              namePrefix + threadNumber.getAndIncrement(),
                              0);
        if (t.isDaemon())
            t.setDaemon(false);
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }
}

註意到,這裏不僅會將守護線程轉變為用戶線程,而且會把優先級轉變為Thread.NORM_PRIORITY。
如下所示,將守護線程采用線程池的方式開啟:

package com.daemon;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DaemonThreadTest
{
    public static void main(String[] args)
    {
        Thread mainThread = new Thread(new Runnable(){
            @Override
            public void run()
            {
                ExecutorService exec = Executors.newCachedThreadPool();
                Thread childThread = new Thread(new ClildThread());
                childThread.setDaemon(true);
                exec.execute(childThread);
                exec.shutdown();
                System.out.println("I‘m main thread...");
            }
        });
        mainThread.start();
    }
}

class ClildThread implements Runnable
{
    @Override
    public void run()
    {
        while(true)
        {
            System.out.println("I‘m child thread..");
            try
            {
                TimeUnit.MILLISECONDS.sleep(1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

運行結果:

I‘m main thread...
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..
I‘m child thread..(無限輸出)

上面代碼證實了線程池會將守護線程轉變為用戶線程。

Java 守護線程概述