在Java中运行多个线程
我遇到了一个很奇怪的问题.我正在做一项作业,其中涉及对在2d棋盘"上移动的图形进行模拟.每个图都由实现Runnable接口的对象表示. 问题是,当我尝试在不同的线程中运行每个对象时,像这样:
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 void run()
{
System.out.println( "Player " + this.hashCode() + " starts moving..." );
...
}
我只从单个对象获取输出.我仔细检查并确保两个ArrayList都包含正确数量的对象. 知道为什么会这样吗?
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?
要启动线程,您必须调用pt.start()
,而不是pt.run()
.有关所有详细信息,请参见JavaDoc.
To start a thread you have to call pt.start()
, not pt.run()
. See the JavaDoc for all the details.