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.
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.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With