我有以下代码..
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class daemonTest {
public static void main(String... a) throws Exception {
ExecutorService service = Executors
.newSingleThreadExecutor(new ThreadFactory() { // anonmyous class start
public Thread newThread(Runnable r) {
Thread two = new Thread(r, "two");
two.setDaemon(true);
System.out.println("two --->" + two.isDaemon());
return two;
}
});
for (int i = 0; i < 10; i++)
service.submit(new Runnable() {
@Override
public void run() {
System.out.println("[" + Thread.currentThread().getName()
+ "] - Hello World.");
Thread.yield();
}
});
service.shutdown();
}
}
,结果的输出是......
two --->true
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
[two] - Hello World.
请告知上面的代码正在做什么..我想要实现的是将一个线程设置为守护进程,然后该守护进程线程将为非守护进程线程提供服务!!
答案 0 :(得分:0)
请告知上面的代码正在做什么..
这是你的代码:
service.submit(new Runnable() {
@Override
public void run() {
System.out.println("[" + Thread.currentThread().getName()
+ "] - Hello World.");
Thread.yield();
}
});
您提交的10个作业println
,yield()
是无关紧要的,然后立即生效。他们不是在等待任何线程。如果你需要它,那么你需要在你的runnable中的某个地方two.join()
。