Java Api之守护线程

/ JAVA API / 没有评论 / 474浏览

守护线程



public class DaemonThreadDemo {
    public static void main(String[] args) {
	 Thread rose = new Thread(){
            public void run() {
                for(int i = 0; i < 5; i++){
                    System.out.println("rose:let me go!");
                    try{
                       Thread.sleep(1000);
                    } catch(InterruptedException e){
                    }
                }            
                System.out.println("rose:啊啊啊啊啊AAAAAaaaaaa!");
                System.out.println("噗通");
            }
        };

        Thread jack = new Thread() {
            public void run() {
                while(true) {
                    System.out.println("jack:you jump! i jump!");
                    try {
                        Thread.sleep(1000);
                    } catch(InterrutedException e) {

                    }
                }
            }
        };
        rose.start();
        /*
         * 设置守护线程必须要在start方法之前进行
         */
        jack.setDaemon(true);
        jack.start();
    }
}

输出结果:


rose:let me go!
jack:you jump! i jump!
rose:let me go!
jack:you jump! i jump!
rose:let me go!
jack:you jump! i jump!
rose:let me go!
jack:you jump! i jump!
rose:let me go!
jack:you jump! i jump!
rose:啊啊啊啊啊AAAAAaaaaaa!
噗通
jack:you jump! i jump!