eduassist
eduassist

Reputation: 1

Concurrency- Difference between starting thread as it is initialized

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

Answers (4)

Ian Roberts
Ian Roberts

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

Sainath S.R
Sainath S.R

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

cs512
cs512

Reputation: 23

The difference should rely on how your OS implements. But in general, there should be no difference.

Upvotes: 0

SMA
SMA

Reputation: 37023

No difference and you cant predict which thread will start in both the case.

Upvotes: 1

Related Questions