【问题标题】:New thread for each item in iterator迭代器中每个项目的新线程
【发布时间】:2020-05-24 18:22:42
【问题描述】:

我有这段代码可以勾选我的 JAVA 游戏,但我需要为迭代器中的每个实体创建一个新线程。

public void tick(){
    player.tick();
    Iterator<Entity> it = entities.iterator();
    while (it.hasNext()) {
        Entity e = it.next();
        e.tick();
    }
}

我尝试了类似的方法,但它根本没有任何好处。

    public void run(){
    entityThread = new Thread();
    entityThread.start();
    running = true;
    Iterator<Entity> it = entities.iterator();

    while(running) {
        player.tick();
        while (it.hasNext()) {
            Entity e = it.next();
            e.tick();

            try {
                entityThread.join();
                System.out.println("vyksta join");
                System.out.println(Thread.currentThread().getName());

            } catch (InterruptedException er) {
                er.printStackTrace();
            }
        }
    }
}

我想过做一个线程池,但迭代器中的东西并不多。有5个实体。我怎样才能做到这一点?

【问题讨论】:

  • 你有什么问题?
  • @user3707125 抱歉,问题是,如何正确地在我的程序中添加多线程?
  • 你应该看看如何创建一个线程,因为你没有正确地做。有关更多指导,请参阅 this 之类的内容。
  • 你想达到什么目的?如果您对 Java 中的正确术语或多线程一无所知,请至少尽力解释您想要什么。不只是问“如何正确地将多线程添加到我的程序中?”.
  • @akuzminykh 我需要为迭代器中的每个实体创建一个新线程,并在程序结束时加入所有线程。

标签: java multithreading


【解决方案1】:

这是您的示例的代码。

public void tick() {
  player.tick();
  Iterator<Entity> it = entities.iterator();
  while (it.hasNext()) {
    Entity e = it.next();
    Runnable task = () ->  e.tick();
    new Thread(task).start();
  }
}

一般来说,您应该避免为每个任务创建线程。考虑使用线程池。

【讨论】:

    【解决方案2】:

    不要遍历“it”迭代器来为每个实体创建一个新线程,而是这样做:

    int n = Iterators.size(it);
    Thread threads[] = new Thread[n];
    for (int j = 0; j < n; j++) {
        threads[j] = new Thread("New Thread"){
        public void run(){
          //place what each thread should do in here
        }
        };
        threads[j].start();
    }
    
    //since you said at the end of program join all threads
    for (int j = 0; j < n; j++) {
    //place the following in a try catch
        threads[j].join();
    }
    

    这里是 more information 关于如何从 Thread 类创建 Thread。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多