Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 984
Russell Avatar asked Dec 28 '22 05:12

Russell


2 Answers

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(...);
like image 58
axtavt Avatar answered Mar 17 '23 02:03

axtavt


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.

like image 33
Tim Avatar answered Mar 17 '23 03:03

Tim