Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

java - Could not start more threads despite using Executors

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();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, 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);

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...