Running multiple threads in Java
I'm having a very weird problem.I'm working on an assignment that involves building a simulation of figures moving on a 2d "chessboard". Each figure is represented by an object implementing the Runnable interface. The problem is that when I attempt to run each object in a different thread like so:
ArrayList< Thread > playerThreads = new ArrayList< Thread >();
ArrayList< Player > players = p.getSpawnedPlayers(); // This method returns all Runnable objects
for ( Player pl : players )
playerThreads.add( new Thread( pl ) );
for ( Thread pt : playerThreads )
{
pt.run();
}
For some reason, only the first thread starts.And I'm pretty certain of this, the run() method of the player class looks like this:
public vo开发者_如何学Goid run()
{
System.out.println( "Player " + this.hashCode() + " starts moving..." );
...
}
I only get output from a single object.I doublechecked and made sure that both ArrayLists contain the right number of objects. Any idea why this is happening?
To start a thread you have to call pt.start()
, not pt.run()
. See the JavaDoc for all the details.
精彩评论