Regarding daemon thread providing some service to non daemon thread

前端 未结 2 945
我在风中等你
我在风中等你 2020-12-22 05:41

I have one query that is I have developed a code below of multiple threads named thread one and thread two, below is the code ..

class multip implements Runnable {

2条回答
  •  温柔的废话
    2020-12-22 06:01

    The question is about of how the daemon thread will provide the service to non daemon thread

    I would use an executor service. If you want to return a value from the daemon thread, you can use a Callable instead of a Runnable.

    // creating a thread pool.
    ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            // creating a thread.
            Thread two = new Thread(r, "two");
            // making it a daemon thread.
            two.setDaemon(true);
            return two;
        }
    });
    
    for(int i=0;i<10;i++)
        // creating a task and submitting it.
        service.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("["+Thread.currentThread().getName()+"] - Hello World.");
                Thread.yield();
            }
        });
    service.shutdown();
    

    prints

    [two] - Hello World.
    [two] - Hello World.
    [two] - Hello World.
    

    First it creates a thread pool with a work queue. The thread pool has a factor which creates threads, in this case with a given name which is a daemon.

    Secondly there is a loop which add 10 tasks to the queue for the executors thread(s) to execute.

    Finally it stops the service when it has finished with it (this is rarely needed)

提交回复
热议问题