[英]Will a thread automatically close after the run() method finishes executing?
I'm currently developing the networking for my game, and have a client and a server running. 我正在为我的游戏开发网络,并且运行客户端和服务器。 The server currently loops infinitely in another
Thread
, but my client and game code are in the same thread. 服务器当前在另一个
Thread
无限循环,但我的客户端和游戏代码在同一个线程中。 I have ran into problems when the client is handling data from the server, and the game hangs until the client is done processing new packets. 当客户端处理来自服务器的数据时,我遇到了问题,游戏一直挂起,直到客户端完成处理新数据包。
I tried to solve this, by making the client class implement Runnable
, and run in a separate thread. 我试图通过使客户端类实现
Runnable
来解决这个问题,并在一个单独的线程中运行。 I have run into some other errors, and am wondering if this is the problem. 我遇到了一些其他错误,我想知道这是不是问题。
I have the run
method, and the sendPacket
method: 我有
run
方法和sendPacket
方法:
public void run() {
// empty
}
public void sendPacket() {
somePacketSendingCode();
}
There is no code in the run
method, as I only use the sendPacket
method. run
方法中没有代码,因为我只使用sendPacket
方法。 sendPacket
is called by a listener thread when a packet is received. 收到数据包时,侦听器线程会调用
sendPacket
。
If I have no code in the run
method, does that mean that the client Thread
stops executing after starting? 如果我在
run
方法中没有代码,那是否意味着客户端Thread
在启动后停止执行? If this is so, doesn't that mean that the sendPacket
method would do nothing? 如果是这样,那是不是意味着
sendPacket
方法什么都不做?
AFAIK, the thread is stopped when the run () method returns. AFAIK,当run()方法返回时,线程停止。 Thread States
线程状态
If you are not calling the sendPacket
method inside the run
method, then it will never execute. 如果不调用
sendPacket
里面方法run
方法,那么它永远不会执行。 The thread stops as soon as run
returns. 一旦
run
返回,线程就会停止。
Note that only the run method contains the actual code of the thread. 请注意,只有run方法包含线程的实际代码。 You said in your post that you have the
sendPacket
method and are only using that one. 你在帖子中说你有
sendPacket
方法并且只使用那个方法。 This means that you are not actually running anything in parallel. 这意味着您实际上并没有并行运行任何东西。 A parallel thread will be fired when you call
start()
, which calls the run
method asynchronously. 调用
start()
时将触发并行线程, start()
将异步调用run
方法。 Calling only sendPacket
is not parallelism. 仅调用
sendPacket
不是并行性。
After a run() method returns, the thread terminates. run()方法返回后,线程终止。 If you have called sendPacket, any packet sent will have been passed to the OS and it will pass on the packets.
如果您已调用sendPacket,则发送的任何数据包都将传递给操作系统,并将传递数据包。 Any packet not sent will have to be sent by another thread or be lost.
任何未发送的数据包都必须由另一个线程发送或丢失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.