NutzCN Logo
问答 关于Nutz异步处理问题
发布于 2800天前 作者 qq_16dd5808 1839 次浏览 复制 上一个帖子 下一个帖子
标签:

我循环了1万次,可是后台只打印了64行日志?怎么回事?

public static void main(String[] args) throws ExecutionException, InterruptedException {
        Sender.setup(null);

        List<Future> list = new ArrayList<Future>();

        for (int i = 0; i < 10000; i++) {
            Request req = Request.create("https://github.com/nutzam/nutz", Request.METHOD.POST);
            Future<Response> response = Sender.create(req).setTimeout(7 * 1000).send(new Callback<Response>() {
                Stopwatch sw = Stopwatch.begin();

                public void invoke(Response resp) {
                    sw.stop();
                    System.out.println(Thread.currentThread().getName() + " " + sw.toString());//怎么只打印了64个?
                }
            });
            list.add(response);
        }

        int i = 0;

        for (Future f : list) {
            System.out.println(++i + "");
        }

        Sender.shutdown();
    }
4 回复
System.out.println(Thread.currentThread().getName() + " " + sw.toString());

这句话不是应该在后台打印1万行么?为啥只有64行。
看了源码,

public static ExecutorService setup(ExecutorService es) {
        if (es != null)
            return es;
        if (es == null)
            es = Executors.newFixedThreadPool(64);
        Sender.es = es;
        return es;
    }

是不是跟

es = Executors.newFixedThreadPool(64);

这里有关

因为主线程退出的时候, 非守护线程全部退

加上这个

        for (Future f : list) {
            System.out.println(++i + "");
			f.get();
        }

@wendal 哦,原来是这样。多谢wendal。

说错, 没看到后面的

Sender.shutdown();

总共64的线程, 因为调用了shutdown,后面的还没来得及运行就over了. 你得等啊

添加回复
请先登陆
回到顶部