需要了解下面一段代码的场景 [英] Need to understand the scenario for below piece of code

查看:36
本文介绍了需要了解下面一段代码的场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的一段代码..

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

结果的输出是...

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!!

推荐答案

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

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

这是您的代码:

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

您正在提交 10 个执行 println 的作业,一个无关紧要的 yield(),然后立即提交.他们不等待任何线程.如果你需要它,那么你需要一个 two.join() 在你的 runnable 中的某个地方.

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.

这篇关于需要了解下面一段代码的场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆