user1049697
user1049697

Reputation: 2509

Java - threads in for loop are not created before the previous one is finished

I am trying to create new threads in a for loop in Java, but a new thread is not started before the previous one is done running. How can I make them all start without waiting for the previous one?

This is the code I am using to start threads:

Thread[] threads = new Thread[processors];
for(int i = 1; i <= processors; i++)
{
    threads[i] = new Thread();
    threads[i].doSomeWork();
    threads[i].run();
}

Upvotes: 0

Views: 58

Answers (3)

Jonathan Rosenne
Jonathan Rosenne

Reputation: 2217

Since you have not indicated any synchronization, the order in which the threads will start is arbitrary and will depend on the particular JVM implementation and may also depend on external factors, depending on what work doSomeWork actually does.

Upvotes: 1

Robin Green
Robin Green

Reputation: 33063

Calling new Thread does not actually create a new thread. It just creates a Thread object. You have to call start() on the thread. But that is also not enough. You also have to tell the Thread what to do.

There are two ways to tell the Thread what to do:

threads[i] = new Thread() {
   @Override public void run() {
     doSomeWork();
   }
};
threads[i].start();

Or

threads[i] = new Thread(new Runnable() {
   @Override public void run() {
     doSomeWork();
   }
});
threads[i].start();

Upvotes: 4

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13535

To start next thread, use threads[i].start(), not threads[i].run().

Upvotes: 1

Related Questions