您的位置:首页 > 产品设计 > UI/UE

setDaemon(true)后就是后台线程(守护线程 ),反之就是前台线程(用户线程)

2011-09-27 09:38 477 查看
1,setDaemon(true)后就是后台线程(守护线程 ),反之就是前台线程(用户线程)

2,后台线程 和 前台线程的区别:在java程序中如果所以的前台线程都已经退出,所有的后台线程自动退出。

TestThread为后台线程:

Java代码

public class ThreadDemo {

public static void main(String[] args) {

Thread t = new TestThread();

t.setDaemon(true);

t.start();

// while(true) {

// System.out.println("main(): "+Thread.currentThread().getName() + " is running");

// }

}

}

class TestThread extends Thread {

public void run() {

while(true) {

System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");

}

}

}

public class ThreadDemo {

public static void main(String[] args) {

Thread t = new TestThread();

t.setDaemon(true);

t.start();

// while(true) {

// System.out.println("main(): "+Thread.currentThread().getName() + " is running");

// }

}

}

class TestThread extends Thread {

public void run() {

while(true) {

System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");

}

}

} 运行当前台线程main退出后自动退出。

TestThread和main一样也是前台线程:

Java代码

public class ThreadDemo {

public static void main(String[] args) {

Thread t = new TestThread();

// t.setDaemon(true);

t.start();

// while(true) {

// System.out.println("main(): "+Thread.currentThread().getName() + " is running");

// }

}

}

class TestThread extends Thread {

public void run() {

while(true) {

System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");

}

}

}

public class ThreadDemo {

public static void main(String[] args) {

Thread t = new TestThread();

// t.setDaemon(true);

t.start();

// while(true) {

// System.out.println("main(): "+Thread.currentThread().getName() + " is running");

// }

}

}

class TestThread extends Thread {

public void run() {

while(true) {

System.out.println("TestThread: "+Thread.currentThread().getName() + " is running");

}

}

}

TestThread 就不会退出。

也就是说,所有的前台线程结束后,所有的后台线程会自动退出。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: