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. 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. I have run into some other errors, and am wondering if this is the problem.
I have the run
method, and the sendPacket
method:
public void run() {
// empty
}
public void sendPacket() {
somePacketSendingCode();
}
There is no code in the run
method, as I only use the sendPacket
method. sendPacket
is called by a listener thread when a packet is received.
If I have no code in the run
method, does that mean that the client Thread
stops executing after starting? If this is so, doesn't that mean that the sendPacket
method would do nothing?
Finishing Threads So when does a thread finish? It happens in one of two cases: all instructions in the Runnable are executed. an uncaught exception is thrown from the run method.
The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.
13. Which of the following events will cause a thread to die? Execution of the run() method is called. Explanation : : A thread dies when the execution of the run( ) method ends.
Once a thread in the thread pool completes its task, it's returned to a queue of waiting threads. From this moment it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. There is only one thread pool per process.
If you are not calling the sendPacket
method inside the run
method, then it will never execute. The thread stops as soon as run
returns.
Note that only the run method contains the actual code of the thread. You said in your post that you have the sendPacket
method and are only using that one. 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. Calling only sendPacket
is not parallelism.
After a run() method returns, the thread terminates. If you have called sendPacket, any packet sent will have been passed to the OS and it will pass on the packets. Any packet not sent will have to be sent by another thread or be lost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With