Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have below piece of code..

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();
    }
}

and the output of the result is ...

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.

Please advise what the above piece of code is doing..as the thing that I want to achieve is setting one thread as daemon and then that daemon thread will provide the service to the non daemon thread!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
156 views
Welcome To Ask or Share your Answers For Others

1 Answer

Please advise what the above piece of code is doing..

Here's your code:

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

You are submitting 10 jobs that do println, a yield() which is extraneous, and then they immediately. They aren't waiting for any threads. If you need it to then you need a two.join() somewhere in your runnable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...