Running multiple threads concurrently
Good day all, for running multiple threads concurrently is it开发者_Python百科 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.
- whats are the best solutions?..
- Are there any pitfalls or performance hit, if one creates different thread objects from a single class?.
Thank you. Tips appreciated as always.
- Take a look at the great
java.util.concurrent
package - 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 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.
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
});
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.
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.
精彩评论