Reputation: 1
I have a quick question on concurrency. I am implementing threads and concurrency via the runnable interface. Is there a difference if I first initialize the threads and then call start separately after they have initialized, or if I initialize the threads and call start from within the same for loop?
Here's an example
for (int i= 0; i < threads.length; i++)
threads[i]= new
Thread(new RunnableThread(this, urls[i]));
for (Thread thread : threads)
thread.start();
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
or
for (int i= 0; i < threads.length; i++) {
threads[i]= new
Thread(new RunnableThread(this, urls[i]));
threads[i].start();
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
}
}
Upvotes: 0
Views: 41
Reputation: 122364
There isn't a general answer, it depends what exactly your RunnableThread
class does in its constructor and its run
method. The first approach guarantees that all the constructor calls will be complete before any of the run
methods start, the second doesn't. Whether or not that is important depends on the details of the code.
Upvotes: 0
Reputation: 3306
No, there is no difference between the two and regarding the order of execution of threads , you can never predict when the Scheduler
chooses a thread to execute or in what order they get executed, so it is a good practice to never have your program logic depend on the order of execution of threads
Upvotes: 0
Reputation: 23
The difference should rely on how your OS implements. But in general, there should be no difference.
Upvotes: 0
Reputation: 37023
No difference and you cant predict which thread will start in both the case.
Upvotes: 1