Alex Rivera | Logout

Running multiple threads concurrently

Asked 2011-05-23T14:34:53.577
15

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.

Edit
Report

1 Answer

18
  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());
}
answered 2011-05-23T14:37:18.837

Your Answer