1

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

2
  • 5
    Use myThread.start(), not myThread.run(). Commented Dec 25, 2012 at 20:52
  • Add objects to the list and call them randomly Commented Dec 25, 2012 at 20:53

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Cratylus.. From OP's explanation, and his code, it is almost clear that his ThreadClass either extends Thread or implements Runnable.
Yes, you're right ThreadClass extends threads. I used start() and suceeded,thanks!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.