创建Thread对象或实际启动线程是否昂贵? [英] Is it expensive to create the Thread object or to actually start the thread?
问题描述
考虑此问题.
现在有许多原因导致创建线程的成本很高,特别是需要分配大量内存并需要注册线程的事实.
Now there are various reasons as why creating a thread is expensive, notably the fact that a lot of memory needs to be allocated and the thread needs to be registered.
现在考虑以下代码:
Thread thread = new Thread(new SomeRunnable());
thread.start();
其中哪一部分是昂贵的"部分?实际创建Thread对象的行还是启动线程的行?或两者?我问的原因是因为我正在编写游戏的服务器组件,并且在辩论是否应该在玩家连接后立即创建Thread对象,并在玩家完成登录后启动线程,还是我俩在播放器完成登录后创建并启动线程.
Which part of that is the "expensive" part? The line that actually creates the Thread object or the line that starts the thread? Or both? The reason why I am asking is because I am writing the server-component of a game and I am debating if I should create the Thread object as soon as the player connects and start the thread once the player finishes logging in, or should I both create and start the thread after the player finishes logging in.
推荐答案
创建Thread
对象非常便宜.您只需支付调用构造函数的代价. start()
方法占用空间(本机调用,堆栈内存等)
Creating a Thread
object is very cheap. You just pay the price of calling the constructor. It's the start()
method that takes up space (native calls, stack memory, etc.)
另一方面,如果创建大量线程,请考虑预先创建(并启动它们)并拥有一个池.这已经为您完成,请查看
On the other hand if you create plenty of threads, consider creating (and starting them) in advance and having a pool. This is already done for you, check out Executors
class.
这篇关于创建Thread对象或实际启动线程是否昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!