尽管使用了执行程序,但无法启动更多线程 [英] Could not start more threads despite using Executors

查看:102
本文介绍了尽管使用了执行程序,但无法启动更多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Executors.newCachedThreadPool()可以在产生过多线程时解决问题。

i have been advised to use Executors.newCachedThreadPool() which will be able to solve problems when over-spawning threads.

但是,当线程数超过特定点时仍然存在错误。无论如何,有没有允许线程在等待系统资源可用时自行等待?

However there is still an error when the number of threads is growing past a certain point. Is there anyway to allow a thread to wait itself while waiting for system resources to be available?

[WARN ] Thread table can't grow past 16383 threads.

[ERROR][thread ] Could not start thread pool-1-thread-16114. errorcode -1
Exception in thread "Main Thread" java.lang.Error: errorcode -1
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:640)
    at java.util.concurrent.ThreadPoolExecutor.addIfUnderMaximumPoolSize(ThreadPoolExecutor.java:727)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:657)
    at sg.java.executors_helloworld.App.main(App.java:15)

public class App {
    public static void main(String args[]) {
        ExecutorService es = Executors.newCachedThreadPool();

        long time = System.currentTimeMillis();

        for (int i = 0; i < 1000000; i++) {
            es.execute(new Car());
        }

        long completedIn = System.currentTimeMillis() - time;

        System.out.println(DurationFormatUtils.formatDuration(completedIn,
                "HH:mm:ss:SS"));
    }
}



public class Car implements Runnable {
    public void run() {
        System.out.println("Car <" + Thread.currentThread().getName()
                + "> doing something");

        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


推荐答案

好吧, newCachedThreadPool


创建一个线程池,该线程池创建新的

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

这听起来像您想要一个具有最大大小的池。例如:

It sounds like you want a pool with a maximum size. For example:

ExecutorService es = Executors.newFixedThreadPool(50);

一次最多可以使用50个线程。 (当然,50可能不是最合适的数字,这取决于您在做什么。)

That will use at most 50 threads at a time. (50 may well not be the right number for you, of course - it depends what you're doing.)

这篇关于尽管使用了执行程序,但无法启动更多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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