开发者

How do I run 10 threads at a time from 100 threads in Java?

I'm using Java 6.

Suppose I create 100 threads, each to complete one task. I want to run 10 threads at a time continuously. This means that if I was running thread 1-10, and thr开发者_Go百科ead 8 finishes, I want to be able to start thread 11 right away, without waiting for 1-10 to join.

How can I do this?

One way around this is probably using the isAlive() method, but I was wondering if I can do this without polling.

Thanks.


Why do you need to do it?

The better way would be to create a pool of 10 threads and submit 100 tasks into it. It will have exactly the same effect - 10 of 100 tasks are running simultaneously.

ExecutorService pool = Executors.newFixedThreadPool(10);

for (int i = 0; i < 100; i++)
    pool.submit(...);


Use an ExecutorService threadpool with 10 thread to submit tasks to. Any jobs you sumit will end up on q Queue, from which the 10 threads will execute your 1000 jobs.


When you say "at a time" while talking about concurrency is Confusing. If you use a ExecuterService with thread pool size of 10, 10 out of 100 threads will be enabled for execution. But remember if you have only 1 CPU and one of your thread has higher priority, all other threads may stay in waiting state. My suggestion is to tune your number threads based on the number of CPU available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜