1. 程式人生 > >JAVA——守護執行緒或使用者執行緒(setDaemon)

JAVA——守護執行緒或使用者執行緒(setDaemon)

這裡寫圖片描述

class StopThread implements Runnable
{
    private boolean flag = true;
    public synchronized void run()
    {
        while(flag)
        {
            try
            {
                wait();
            }
            catch(InterruptedException e)
            {
                System.out.println(Thread.currentThread().getName()+"....Exception"
); flag = false; } System.out.println(Thread.currentThread().getName()+"....run"); } } public void changeFlag() { flag = false; } }
class StopThreadDemo
{
    public static void main(String[] args)
    {
        StopThread st = new
StopThread(); Thread t1 = new Thread(st); Thread t2 = new Thread(st); t1.start(); t2.start(); int num = 0; while(true) { if(num++==10) { st.changeFlag(); break; } System.out
.println(Thread.currentThread().getName()+"....main"+num); } } }

輸出結果:
這裡寫圖片描述
卡著不動了。
現在修改程式:線上程開啟之前加上守護執行緒。
這裡寫圖片描述
因為後臺執行緒依賴於前臺執行緒,當主執行緒掛了,後臺執行緒就不復存在了。因此程式可以終止。