Rexx
Rexx

Reputation: 269

Running multiple threads concurrently

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.

Upvotes: 15

Views: 41073

Answers (5)

Boris Pavlović
Boris Pavlović

Reputation: 64650

  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());
}

Upvotes: 18

meisam
meisam

Reputation: 11846

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.

Upvotes: 0

Kevin
Kevin

Reputation: 25269

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
});

Upvotes: 3

Ted Hopp
Ted Hopp

Reputation: 234857

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.

Upvotes: 2

Saurabh Gokhale
Saurabh Gokhale

Reputation: 46425

I would personally go for option(1) (Creating 2 different threads of the same class).

I don't feel there's need to create 2 different classes for the job that can be done by 2 different threads of the same class.

Upvotes: 3

Related Questions