简体   繁体   English

在我的情况下,我应该使用线程池代替池吗?

[英]Should I use Thread Pool instead pool in my situation?

I have simple Tower Defence game. 我有简单的塔防游戏。 Every monster moves in it's own thread so when new wave comes about 20 new threads are done (from 10 to 25, randomly). 每个怪物都在它自己的线程中移动,所以当新的波浪出现时,大约有20个新线程被完成(从10到25,随机)。 I remember something like executor class which is useful in situations when there are many-short lived threads. 我记得像执行器类这样的东西,它在有很多短寿命线程的情况下很有用。 Like I have. 就像我一样。 So my questions are: 所以我的问题是:

  1. Should I use thread pool and how much would it increase perofrmance? 我应该使用线程池,它会增加多少性能?
  2. How should I implement it? 我该如何实施呢? Should pool be a field? 池应该是一个领域吗?

I would have a move() method for each monster and call it periodically. 我会为每个怪物设置一个move()方法并定期调用它。 This way you have just one thread and it should perform just fine. 这样你只有一个线程,它应该执行得很好。 BTW That one thread can use an ExecutorService if you like. BTW如果你愿意,一个线程可以使用ExecutorService。

I think it is safe to assume that the interval between waves is more than one second, isn't it? 我认为可以安全地假设波之间的间隔超过一秒,不是吗? Otherwise, your game would be quite hard to beat. 否则,你的游戏将很难被击败。 ;-) ;-)

I would not expect that using a thread pool will make a difference if you spawn so few threads (15-25 threads are not a big deal). 如果你产生如此少的线程(15-25个线程不是什么大问题),我不希望使用线程池会产生影响。 Personally, I would just use new Thread . 就个人而言,我只会使用new Thread You can always switch to an ExecutorService later, but I don't think it is needed in your scenario. 您可以随时切换到ExecutorService ,但我不认为您的方案中需要它。

A thread pool is reasonable when you are writing, for example, a web server that has to process several hundred of incoming requests (assuming that each request should be handled in a separate thread). 编写时,线程池是合理的,例如,必须处理数百个传入请求的Web服务器(假设每个请求都应在单独的线程中处理)。 Then a thread pool will likely increase performance but its most important advantage is that it is a handy way to limit resource usage. 然后线程池可能会提高性能,但其最重要的优点是它是一种限制资源使用的便捷方式。

Why? 为什么? If you would just spawn a new thread on each request, you risk that you will soon run out of resources if there are many requests at the same time. 如果您只是在每个请求上生成一个新线程,那么如果同时有多个请求,您将很快就会耗尽资源。 Using a thread pool with an upper limit of threads prevents that from happening. 使用具有线程上限的线程池可防止发生这种情况。

(However, without knowing the details of your application, from a pure design perspective, avoiding threads completely and keeping all the game logic in one thread is definitely something that you should consider. It will make things much simpler. But again, I don't have the details.) (但是,在不了解应用程序的详细信息的情况下,从纯粹的设计角度来看,完全避免线程并将所有游戏逻辑保留在一个线程中绝对是您应该考虑的事情。它会使事情变得更简单。但是,我再说一遍有详细信息。)

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

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