java--多執行緒之後臺執行緒

滄海一滴發表於2013-11-01

public
class ThreadDaemon { /** * @param args * 後臺執行緒在主程式結束後,也會退出 */ public static void main(String[] args) { // TODO Auto-generated method stub ThreadImplementsTest tlt=new ThreadImplementsTest(); Thread t1=new Thread(tlt); t1.setName("Daemon Thread test"); t1.setDaemon(true);//如果一個程式中只用後臺執行緒在執行,那麼整個程式就會結束。 t1.start(); } }
Output:

exit
Daemon Thread test====>進入loop()
0

 

 

public class ThreadImplementsTest implements Runnable{
    
    public void loop(){
        String name=Thread.currentThread().getName();
        System.out.println(name+"====>進入loop()");
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println(i);
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                System.out.println(e.getLocalizedMessage());
                System.out.println(e.getMessage());
                e.printStackTrace();
            }
        }
        System.out.println(name+"=============>離開Loop");
    }
    

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ThreadImplementsTest tst=new ThreadImplementsTest();
        tst.run();
        
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        tst.loop();
    }

    public void run() {
        // TODO Auto-generated method stub
        loop();
    }
}

相關文章