I’m trying to move my client network processing code into another thread, so it doesn’t hang the main thread when processing a packet.
Basically I have an ArrayList of packets received. The Thread runs an infinite while loop, processing any new packets. However this puts my CPU up to 100%, because even if there are no new packets, it still loops continuously.
What I want to do, is have the processing thread sleeping, and my thread, notify it, when there are new packets.
I’m coding this in Java.
EDIT:
This is what I am striving to achieve –
// Main Thread
// Listener
public void newPacketReceived(){
receiverThread.addNewPacketToProcessingQueue(null);
}
// Receiver Thread
ArrayList<GamePacket> processingQueue = new ArrayList<GamePacket>();
public void addNewPacketToProcessingQueue(GamePacket packet){
processingQueue.add(packet);
this.notify();
}
public void run(){
while(true){
// Process Packets
this.sleep(); // Sleep until thread is notified
}
}
Rather than using an
ArrayList, use aBlockingQueueof some description (e.g.LinkedBlockingQueue). That’s designed for exactly this sort of use case.The producer code will use
offerto offer a new element, and the processing thread will usepollwith a timeout to block (cheaply) until an element is present.