尽管使用了Executors,但无法启动更多线程

时间:2011-07-31 06:53:07

标签: java multithreading concurrency executor

我被建议使用Executors.newCachedThreadPool(),它可以在过度产生线程时解决问题。

然而,当线程数增长超过某一点时仍然存在错误。反正是否允许线程在等待系统资源可用时等待自己?

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

1 个答案:

答案 0 :(得分:4)

好吧,newCachedThreadPool

  

创建一个根据需要创建新线程的线程池,但在它们可用时将重用以前构造的线程。

听起来你想要一个最大尺寸的游泳池。例如:

ExecutorService es = Executors.newFixedThreadPool(50);

一次最多使用50个线程。 (50可能不适合你,当然 - 这取决于你正在做什么。)