从while循环中运行的线程获取值

问题描述 投票:0回答:1

我有一个java线程,它在一个常量while循环中运行一个路径查找算法。然后,我经常想从线程中检索最新的路径。但是,我不确定如何做到这一点,并认为我可能做错了。我的主题包含以下代码:

public class BotThread extends Thread {

  Bot bot;
  AStar pathFinder;
  Player targetPlayer;
  public List<boolean[]> plan;

  public BotThread(Bot bot) {
    this.bot = bot;
    this.plan = new ArrayList<>();
    pathFinder = new AStar(bot, bot.getLevelHandler());
  }

  public void run() {
    while (true) {
      System.out.println("THREAD RUNNING");
      targetPlayer = bot.targetPlayer;
      plan = pathFinder.optimise(targetPlayer);
    }
  }

  public boolean[] getNextAction() {
    return plan.remove(0);
  }

}

然后我创建一个BotThread的对象,并调用start()。然后当我在线程上调用getNextAction()时,我似乎收到一个空指针。这是因为我在主循环中无法在线程上调用另一个方法吗?我该怎么做呢?

multithreading java-threads
1个回答
0
投票

这是因为你没有足够的时间来初始化计划Arraylist。您需要为线程添加休眠时间。从main调用BotThread类时这样的事情:

     int num_threads = 8; 
     BotThread myt[] = new BotThread[num_threads];
        for (int i = 0; i < num_threads; ++i) {
            myt[i] = new BotThread();
            myt[i].start();
            Thread.sleep(1000);
            myt[i].getNextAction();

        }
© www.soinside.com 2019 - 2024. All rights reserved.