Its just a classical producer consumer problem, and you must be seeking a better implementation than you did.
In your case if you are using a positive value for sleep
then you have already done saving CPU for other processes to also use it since high CPU usage is good (see Note at the bottom for clarity).
If you are looking for optimization and better performance then you need to tweak your code specific to your application needs, here are two suggestions.
You might use signaling in threads (also call inter-thread communication) using wait and notify calls if you can convert msg
to a thread-safe queue; this way you can overcome arbitrary waiting.
If your processing on the msg
items (that you perform in for
loop) is IO hungry then you can try splitting in independent threads or you can upgrade your code to do async processing.
Note: If you have a high CPU usage then it means you are best using your computing resources, but it can lead to deprived reliability down the line and starvation of resources for other process which might be bad hence try putting priority on your threads/process as per your needs are.