Running multiple threads in Java

泄露秘密 提交于 2019-12-11 06:23:01

问题


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..." );
    ...
}

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?


回答1:


To start a thread you have to call pt.start(), not pt.run(). See the JavaDoc for all the details.



来源:https://stackoverflow.com/questions/4235487/running-multiple-threads-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!