简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM