Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

java - Need to understand the scenario for below piece of code

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...