Thread parent = currentThread(); this.daemon = parent.isDaemon();
public final void setDaemon(boolean on) {
checkAccess(); if (isAlive()) {
throw new IllegalThreadStateException(); } daemon = on; }
例1:thread是用户线程,主线程结束后,thread会继续运行
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new Runnable() {
@Override public void run() {
while (true) {
try {
Thread.sleep(1000L); System.out.println("still running."); } catch (InterruptedException e) {
e.printStackTrace(); } } } }); //设置线程为用户线程 thread.setDaemon(false); thread.start(); Thread.sleep(3000L); System.out.println("主线程退出"); } //输出 still running. still running. 主线程退出 still running. still running. still running. still running.
例2:thread是守护线程,主线程结束后,thread会随即停止
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new Runnable() {
@Override public void run() {
while (true) {
try {
Thread.sleep(1000L); System.out.println("still running."); } catch (InterruptedException e) {
e.printStackTrace(); } } } }); //设置线程为守护线程 thread.setDaemon(true); thread.start(); Thread.sleep(3000L); System.out.println("主线程退出"); } //输出 still running. still running. 主线程退出
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224297.html原文链接:https://javaforall.net
