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
Use
Thread.start()rather thanThread.run(). Using therunmethod simply calls that method in the same thread, whereas thestartmethod actually creates a new thread and calls therunmethod within that thread.I assume by “randomly”, you actually mean interleaving. This should lead to that result.