2

I have 2 classes that implement Runnable.I need to create 10 threads to execute them.I use the following code.

ExecutorService es = Executors.newFixedThreadPool(10);
  Runnable r=new TestThread1();
  Runnable r1=new TestThread2();
  es.execute(r);
  es.execute(r1);

but since only 2 runnables exist,only 2 threads are being used to execute.how shud i increase the no of threads

3
  • Do you mean that you want to run each Runnable on 5 threads? Commented Jan 27, 2011 at 8:26
  • yes...i ve to assign more threads for a single runnable Commented Jan 27, 2011 at 9:14
  • I've a feeling that you want to make one runnable use multiple threads - that can't happen. To 'spread' a task over multiple threads, you need to re-write the code. Commented Jan 27, 2011 at 13:56

3 Answers 3

3

Threads will be created as you submit more jobs to the executor. If the number of submitted jobs exceed 10 (in this case), the new jobs will be queued. When threads become free they will be used to run the queued jobs. If you want the executor to create 10 threads, you need to submit 10 jobs:

for (int i = 0; i < 5; ++i) {
    if (!es.isShutdown()) {
        es.submit(new TestThread1());
        es.submit(new TestThread2());
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have a few database insert statements in 2 runnable classes.As jobs are inside a loop iterated 5 times,i ve each value being inserted 5 times.i want this to be avoided
You shouldn't need to check whether its shutdown as the ExecutorService has a rejection policy which you can change to handle this case.
1

One Runnable can only run on one Thread. It doesn't get split up across multiple threads automatically.

If you want to utilise your entire thread pool, create more runnable objects.

Comments

0

Executors.newFixedThreadPool(size) returns ThreadPoolExecutor instance.

JavaDoc of ThreadPoolExecutor says: ” When a new task is submitted in method ThreadPoolExecutor.execute, and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle.”

That is, you have to execute 10 threads to fill the pool.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.