-1

我有下面的代码..

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.

请告知上面的代码在做什么......因为我想要实现的是将一个线程设置为守护程序,然后该守护程序线程将为非守护程序线程提供服务!

4

1 回答 1

0

请告知上面的代码在做什么..

这是你的代码:

        service.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("[" + Thread.currentThread().getName()
                        + "] - Hello World.");
                Thread.yield();
            }
        });

您正在提交 10 个工作,其中println一个yield()是无关的,然后立即提交。他们不等待任何线程。如果你需要它,那么你需要two.join()在你的可运行文件中的某个地方。

于 2012-07-26T16:18:12.373 回答