Reputation: 269
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.
Thank you. Tips appreciated as always.
Upvotes: 15
Views: 41073
Reputation: 64650
java.util.concurrent
packageHere'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
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
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
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
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