[英]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". 我遇到一个非常奇怪的问题。我正在做一个作业,其中涉及建立在2d“棋盘”上移动的图形的模拟。 Each figure is represented by an object implementing the Runnable interface.
每个图都由实现Runnable接口的对象表示。 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: 出于某种原因,只有第一个线程启动。而且我敢肯定,player类的run()方法如下所示:
public void 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. 我只从单个对象获得输出。我仔细检查并确保两个ArrayList都包含正确数量的对象。 Any idea why this is happening?
知道为什么会这样吗?
To start a thread you have to call pt.start()
, not pt.run()
. 要启动线程,您必须调用
pt.start()
而不是pt.run()
。 See the JavaDoc for all the details. 有关所有详细信息,请参见JavaDoc。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.