java多线程之后台线程

来源:互联网 发布:数据库中的存储过程 编辑:程序博客网 时间:2024/06/05 05:01

1.后台线程

在后台运行的线程,其目的是为其他线程提供服务,也称为“守护线程"JVM的垃圾回收线程就是典型的后台线程。

特点:若所有的前台线程都死亡,后台线程自动死亡,前台线程没有结束,后台线程是不会结束的。测试线程对象是否为后台线程:使用thread.isDaemon()。前台线程创建的线程默认是前台线程,可以通过setDaenon(true)方法设置为后台线程,并且当且仅当后台线程创建的新线程时,新线程是后台线程。

设置后台线程:thread.setDaemon(true),该方法必须在start方法调用前,否则出现IllegalThreadStateException异常。

//后台线程class DaemonThread implements Runnable {public void run() {for (int i = 0; i < 50; i++) {System.out.println("后台线程" + i);}}}//主线程public class ThreadDemo12 {public static void main(String[] args) {System.out.println("主线程是后台线程么:"+Thread.currentThread().isDaemon());for (int i = 0; i < 50; i++) {System.out.println("主线程"+i);if (i==10) {Thread thread = new Thread(new DaemonThread());thread.setDaemon(true); //设置为后台线程,必须在start()方法之前调用thread.start();}}}}