How to start 10 threads at a time from 100 threads in Java?

I am using Java 6.

Suppose I create 100 threads, each of which performs one task. I want to run 10 threads at a time. This means that if I were working with thread 1-10 and ending with thread 8, I want to immediately start thread 11, without waiting for 1-10 to join.

How can i do this?

One way might use the isAlive () method, but I was wondering if I could do this without polling.

Thank.

+3
source share
3 answers

Why do you need this?

It is best to create a pool of 10 threads and send 100 tasks to it. It will have exactly the same effect: 10 out of 100 tasks are performed simultaneously.

ExecutorService pool = Executors.newFixedThreadPool(10);

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

ExecutorService threadpool 10 . , , q Queue, 10 1000 .

+1

When you say β€œat a time” when it comes to concurrency, this is Confusing. If you use an ExecuterService with a thread pool size of 10, 10 out of 100 threads will be included for execution. But remember, if you have only one processor, and one of your threads has a higher priority, all other threads can remain in a waiting state. My suggestion is to configure the number of threads based on the number of CPUs available.

0
source

Source: https://habr.com/ru/post/1775285/


All Articles