java中的后台线程,是Thread实例设置了setDaemon(true),即将daemon属性设置为了true。 主线程运行结束,后台线程会被jvm中断,退出程序。
public static void main(String[] args) { Thread thread = new Thread() { @Override public void run() { while (true) { try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread run"); } } }; //设置线程为守护线程 thread.setDaemon(true); thread.start(); try { Thread.sleep(3 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main end"); }
运行结果:
thread runthread run
main end
thread run
Process finished with exit code 0
可以看到在主线程退出之后,deamon线程也就被终止了,同时程序也就退出了。
我们对上面程序稍作改动,将t.setDaemon(true)注释掉,再看下运行结果。
public static void main(String[] args) { Thread thread = new Thread() { @Override public void run() { while (true) { try { Thread.sleep(1 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("thread run"); } } }; //设置线程为守护线程 // thread.setDaemon(true); thread.start(); try { Thread.sleep(3 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main end"); }
运行结果:
thread run
thread run
main end
thread run
thread run
thread run
thread run
thread run
thread run
thread run
thread run
thread run
thread run
可以看到在主线程退出之后,子线程还在继续执行,这是因为线程t默认情况下是非守护线程,尽管主线程退出了,他还是在继续执行着。