two - thread pool implementation in java




Running multiple threads concurrently (4)

Good day all, for running multiple threads concurrently is it advisable to create different thread objects from a class or create two classes where one implements runnable and one extends a thread and then create thread objects from both of them as needed assuming we are trying to run 7- 10 tasks concurrently.

  1. whats are the best solutions?..
  2. Are there any pitfalls or performance hit, if one creates different thread objects from a single class?.

Thank you. Tips appreciated as always.


  1. Take a look at the great java.util.concurrent package
  2. There are no performance pitfalls out of creating different thread objects from a single class

Here's a short example:

private static class SomeTask implements Runnable
{
  @Override
  public void run()
  {
    doSomething();
  }
}

public static void main(String[] args)
{
  ExecutorService executor = Executors.newCachedThreadPool();
  for (int i = 0; i < 8; i++) executor.execute(new SomeTask());
}

I don't think it matters which way you do it. If you're going to be having a lot of short lived threads you'll probably want a thread pool, see java.util.concurrent.Executors. Usually I create an annonymous class of type runnable, e.g.

executor.execute(new Runnable() {
    //thread code goes here
});

The main thing that makes the difference is how you have designed your object hierarchy: If you extend Thread class, you can't extend any other classes (Java is single Inheritance). so by Implementing the Runnable, you can still extend other classes in your domain model.


There's little difference in performance between creating a thread by extending Thread or by implementing Runnable and using new Thread(runnable). Whether using one class or several is also irrelevant. You should design your class structure based on the work to be done; if two threads are doing the same work on different data, use the same class for both.

Access to shared data (whether static class variables or something else) is always a big issue.







multithreading