0

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

1 に答える 1

4

さて、newCachedThreadPool:

必要に応じて新しいスレッドを作成するスレッド プールを作成しますが、以前に構築されたスレッドが利用可能になった場合はそれらを再利用します。

最大サイズのプールが必要なようです。例えば:

ExecutorService es = Executors.newFixedThreadPool(50);

これにより、一度に最大 50 のスレッドが使用されます。(もちろん、50 という数字は適切ではないかもしれません。何をしているかにもよります。)

于 2011-07-31T06:58:30.053 に答える