Hey everyone. I'm new to Java, so I thought a cool way to learn would be to write a chat client. I'm happy to report that it's going pretty good, except for one major problem.
When I'm ready for the program to connect, it'll start up a thread for handling socket communications. The thread will start by sending the initial handshake and enter a loop for incoming messages. The problem is that it starts consuming processor avalibility, so that nothing else will work until I exit the program. How do I prevent this from happening?
how are you reading these messages from the other end? in most cases, a network client/server program will use a read() or readLine() or readObject() method on some stream or Reader object, and these methods will block quietly until there's input to be had. why aren't yours blocking?
Can you post the code that performs the reading? That would increase help us to help you.
I do have a guess, though. Are you calling available() on the Socket's InputStream inside a loop until it returns a value greater than zero? This would cause the thread to greedily eat up CPU cycles until some data arrived.
Replace the loop and available() call with a call to one of the read() methods. If there is no data available, the thread will sleep (no CPU time taken) until data arrives. At that point the JVM wakes the thread so it can continue with the read() call.