ruslanys
ruslanys

Reputation: 1209

Java Multithreading (10 or more?)

Is it true that it is undesirable to create more than 10 additional threads? Example:

for(int i=0; i<100; i++) {
    new Thread() {
        public void run() {
            // something
        }
    }.start();
}

that will create and start 100 threads. That is not good, right?

UPDATE > Every thread are downloading something and put it into the bundle

Upvotes: 1

Views: 182

Answers (4)

Eugene
Eugene

Reputation: 120848

What you probably want is a ThreadPool instead of creating so many Threads.

For example:

 ExecutorService executor = Executors.newFixedThreadPool(4);
 executor.submit(YourRunnable);

Look more into Thread Pools - they will make your life easier.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

It is undesirable to create more thread than you need.

Of course if you need 100 threads, then that is a good number to create.

No idea where you get it is undesirable to create more than 10 additional threads from. Java processes can handle 10,000 threads.

Upvotes: 6

Dimitri
Dimitri

Reputation: 8280

It will be more easier and faster if you use a thread pool of 10 threads and pass them the correct Runnable.

Upvotes: 2

Science_Fiction
Science_Fiction

Reputation: 3433

Depends entirely on the context. If most the work you are doing is cpu bound then probably wont make much difference or actually make things worse (context switching etc) unless you actually have 100 cores. If a lot of time is spent on I/O tasks, then threading may be beneficial. You really need to do some benchmarking.

Upvotes: 1

Related Questions