在Java中运行多个线程 [英] Running multiple threads in Java

查看:183
本文介绍了在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.

这篇关于在Java中运行多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆