今晚在看Think In Java的时候,看到后台线程这一小节,突然有个想法,如果在一个后台线程里面创建一个非后台线程(不显示的设置setDaemon(true)),
那么创建的非后台线程是否也变成了后台线程。
1、如果在线程中使用Thread开启一个线程:
<pre name="code" class="java">package com.hq.day0601;
import java.util.concurrent.TimeUnit;
/**
* 简单的后台线程(守护线程)练习,该练习主要演示的是后台线程在最后一个非后台线程结束后,也会被关闭
* @author Administrator
*
*/
public class SimpleDaemons implements Runnable {
@Override
public void run() {
try {
<span style="white-space:pre"> </span>//创建一个新的线程
Thread thread = new Thread(new TestThread());
thread.run();
while(true){
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("SimpleDaemons is Daemons:"+Thread.currentThread().isDaemon());
System.out.println(Thread.currentThread() +" "+this );
}
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("sleep() Interrupted");
}
}
public static void main(String[] args) throws Exception {
for(int i = 0 ; i < 3;i++){
Thread daemons = new Thread(new SimpleDaemons());
daemons.setDaemon(true);
daemons.start();
}
System.out.println("daemons start!");
TimeUnit.SECONDS.sleep(1);
}
}
/**
* 校验守护线程中创建的线程是否是守护线程
* @author Administrator
*
*/
class TestThread implements Runnable {
@Override
public void run() {
System.out.println("TestThread is Daemon:"+Thread.currentThread().isDaemon());
}
}
运行结果如下:
<img src="https://img-blog.csdn.net/20160915225643951?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
说明如果使用这种方式,那么在后台线程中创建一个线程,也是守护线程
2.开启线程池的方式
代码如下:
<pre name="code" class="java">package com.hq.day0601;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 简单的后台线程(守护线程)练习,该练习主要演示的是后台线程在最后一个非后台线程结束后,也会被关闭
* @author Administrator
*
*/
public class SimpleDaemons implements Runnable {
@Override
public void run() {
try {
<span style="white-space:pre"> </span>//使用线程池的方式创建
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new TestThread());
exec.shutdown();//关闭线程池
TimeUnit.MILLISECONDS.sleep(100);
System.out.println("SimpleDaemons is Daemons:"+Thread.currentThread().isDaemon());
System.out.println(Thread.currentThread() +" "+this );
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("sleep() Interrupted");
}
}
public static void main(String[] args) throws Exception {
for(int i = 0 ; i < 3;i++){
Thread daemons = new Thread(new SimpleDaemons());
daemons.setDaemon(true);
daemons.start();
}
System.out.println("daemons start!");
TimeUnit.SECONDS.sleep(1);
}
}
/**
* 校验守护线程中创建的线程是否是守护线程
* @author Administrator
*
*/
class TestThread implements Runnable {
@Override
public void run() {
System.out.println("TestThread is Daemon:"+Thread.currentThread().isDaemon());
}
}
打印结果如下:
从结果打印可以看出,使用线程池创建的线程,不是后台线程。
综上所述:
1、后台线程中使用thread创建线程,创建的线程也是后台线程
2、在后台线程中使用线程池创建线程,与后台线程无关。