Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 798
Rexx Avatar asked May 23 '11 14:05

Rexx


People also ask

Can two threads run on same core?

It's up to the OS where a thread is scheduled. There are advantages to keeping a thread on the same core if possible, in terms of cache coherency etc — but forcing it to stay on the same core is usually overly restrictive. In short: yes, a thread can run on different cores.

Is it better to run one thread or multi thread on one?

So when processing a task in a thread is trivial, the cost of creating a thread will create more overhead than distributing the task. This is one case where a single thread will be faster than multithreading.


1 Answers

  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());
}
like image 108
Boris Pavlović Avatar answered Oct 17 '22 08:10

Boris Pavlović