简体   繁体   English

多线程,计算正在运行的线程数

[英]Multiple threads, counting number of running threads

I'm building an RL ai for checkers (so ill be running a lot of different games), and each thread will run a game separately on its own. 我正在为跳棋构建RL ai(因此会运行很多不同的游戏),并且每个线程将单独运行一个游戏。 Im trying to limit the amount of running threads. 我试图限制运行线程的数量。 So if the amount of running threads is less than a certain amount ( threadAmount ): then create a new thread and run a new game, else: don't do anything and wait. 因此,如果正在运行的线程数量少于某个特定数量( threadAmount ):然后创建一个新线程并运行一个新游戏,否则:不要执行任何操作并等待。

for (int i = 0; i < population.size(); i++) {
    int runningThreads = 0;
    for (int j = i; j < population.size(); j++) if (population.get(j).gameOver == false) runningThreads++; //for each running thread, add 1 to runningThreads
    if (runningThreads < threadAmount){ //threadAmount == max # of threads
      population.get(i).gameOver = false;
      Thread newThread = new Thread(population.get(i));
      newThread.start();
      println("\tnew thread started | "+runningThreads);
      delay(100);
    }
    else{
      i--; //retry this 
    }
  }

The problem is that it just creates all the threads willy nilly, the println shows "new thread started | 0" 25 times and the runningThreads var doesn't seem to increase in the for loop at all, and just stays at 0. Unsure what to do :/, but I know this is Processing and that its not thread safe so im ready to pull some fancy smancy stuff to get it done. 问题在于它只会创建所有线程,而println显示“新线程已开始| 0” 25次,并且runningThreads var似乎在for循环中根本没有增加,而是一直保持在0。来做:/,但是我知道这是处理中的,它不是线程安全的,所以即时消息准备好拉一些花哨的东西来完成它。

If I understood correctly, these are your requirements: 如果我理解正确,那么您的要求是:

  • Run each game in a separate Thread . 在单独的Thread运行每个游戏。
  • Never allow more than n games (or Thread s) to run at the same time. 切勿同时运行n游戏(或Thread )。
  • If the maximum number of games are currently running, wait until one or more finish then run the new game. 如果当前正在运行最大数量的游戏,请等到一个或多个完成后再运行新游戏。

The last bullet point is not entirely clear. 最后一点不是很清楚。 It could mean the game should be queued for execution or it could mean the scheduling Thread should block until "space" becomes available. 这可能意味着游戏应该排队等待执行, 或者可能意味着调度Thread应该阻塞,直到“空间”可用为止。

In the first case (queuing) this can be easily solved by using an ExecutorService configured to have no more than n threads. 在第一种情况(排队)中,可以通过使用配置为不超过n线程的ExecutorService轻松解决此问题。 Any tasks submitted while all threads are busy will be queued until a thread becomes available. 所有线程繁忙时提交的所有任务都将排队,直到一个线程可用为止。

ExecutorService executor = Executors.newFixedThreadPool(threadAmount);
for (Runnable r : population) {
    executor.execute(r);
}
executor.shutdown(); // If you won't be using it later

This also has the added benefit of reusing Thread instances rather than creating a new Thread for each game. 这还具有重用Thread实例而不是为每个游戏创建一个新的Thread的额外好处。

As I said in the comments, here is a code sample but its in c#, i have no java code currently. 正如我在评论中所说,这是一个代码示例,但是在c#中,我目前没有Java代码。 But it should work similarly 但它应该类似地工作

List<Task> lTask = new List<Task>();

Worker w = new Worker(msg);
Task t = new Task(() => w.DoWork());
            t.Start();
            lTask.Add(t);`.

I keeping added tasks to the global list. 我将添加的任务保留到全局列表中。 ANd in a timer, I periodically check if anyone of the task (aka thread) expires, 在计时器中,我会定期检查任务(aka线程)是否已过期,

foreach(Task t in lTask)
                {
                    if (!t.Status.Equals(TaskStatus.Running))
                    {
                        // This thread is running... do whatever you do
                    }

                }

Thats my way to work with muti threads, and keep log of their life. 这就是我使用多线程的方式,并记录它们的生活。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM