Avrum
Avrum

Reputation: 259

Create an array if threads in java and run

I have a function that creates several threads.For each thread,a constructor takes an object from a different class, so I have first to create an object of this class and then create the thread. Below the code(modified for the simplification of example)

public static void createThread (int n) {
      for(int i=0;i<n;i++){
         someClass obj=new someClass(i);
         ThreadClass myThread=new ThreadClass(obj);
         myThread.run();
        }

The problem here is that I don't really see that threads are running randomly. I am printing each one of them on run() and I see that they are displayed in their order. Is anything wrong with this? Should I run it differently?

Thanks

Upvotes: 1

Views: 4602

Answers (1)

Ryan Amos
Ryan Amos

Reputation: 5452

Use Thread.start() rather than Thread.run(). Using the run method simply calls that method in the same thread, whereas the start method actually creates a new thread and calls the run method within that thread.

I assume by "randomly", you actually mean interleaving. This should lead to that result.

Upvotes: 9

Related Questions