Java基础多线程之后台守护线程,setDaemon(true)

class DaemonThreadDemo
{
    public static void main(String[] args)
    {
        StopThread stopThread = new StopThread();
    
        Thread t1 = new Thread(stopThread,"t1");
        Thread t2 = new Thread(stopThread,"t2");
        
        t1.setDaemon(true);
        t2.setDaemon(true);
        
        t1.start();
        t2.start();
        
        int num=0;
        while(true)
        {
            if(num++ ==60)
            {            
                stopThread.changeFlag();
                break;
            }
            
            System.out.println(Thread.currentThread().getName()+ " runing.... "+ num);
        }
        
        System.out.println("end");
    }
}

class StopThread implements Runnable
{
    private boolean flag = true;
    public synchronized void run()
    {        
        while(this.flag)
        {
            try
            {
                wait();
            }
            catch(InterruptedException ex)
            {
                System.out.println(Thread.currentThread().getName() + ": Exception");
                this.changeFlag();
            }
            System.out.println(Thread.currentThread().getName() + ": runing...");
        }
    }
    
    public void changeFlag()
    {
        this.flag = false;
    }
}
posted @ 2013-01-15 13:16  陈晓明  阅读(563)  评论(0编辑  收藏  举报