[Java] Thread.setDaemon(boolean) 后台进程

public class Thread5{    
         public static void main(String[] args){    
                Thread t1 = new RunnableTest5(10);    
                t1.setName( "用户线程t1");    
                t1.start();    
                
                Thread t2 = new RunnableTest5(100);    
                t2.setDaemon( true); //设置为后能进程    
                t2.setName( "后台线程t2");    
                t2.start();    
                
                 for( int i=0;i<10;i++){    
                        System.out.println(Thread.currentThread().getName()+ ":"+i);    
                }    
                System.out.println(Thread.currentThread().getName()+ "结束了");    
        }    
}

class RunnableTest5 extends Thread{    
         private int n;    
         public RunnableTest5( int n){    
                 this.n = n;    
        }    
        @Override    
                 public void run(){    
                         for( int i=0;i<n;i++){    
                                System.out.println( this.getName()+ ":"+i);    
                        }    
                        System.out.println( this.getName()+ "结束");    
                }    
}    
//运行结果,main进程和t1进程都会运行完,但是设置成后台进程的t2将不一定运行完    
//java虚拟机会在用户进程和main进程结束后,就退出java虚拟机,所以 后台进程不能执行完

你可能感兴趣的:(java,用户,职场,Java学习,java笔记,休闲)