I've written the following code, but I feel I'm going wrong somewhere:
public class ProcessQueue { static BlockingQueue<String> queue = new LinkedBlockingQueue<String>(); public ProcessQueue() { process(); } public void add(String message) throws InterruptedException { System.out.println("Added Queue size:" + queue.size()); System.out.println("Locked by Producer"); queue.put(message); System.out.println("Lock Released by Producer"); } public static void process() { new Thread() { @Override public void run() { try { while (true) { System.out.println("Locked by Consumer"); Message.send(queue.take()); System.out.println("Locked Released by Consumer"); System.out.println("Consuming Queue size:" + queue.size()); } } catch (Exception ex) { System.out.print(ex.getMessage()); } } }.start(); } } Here add(String) adds the string to the queue. It is called whenever it receives an input from a UDP port. process() processes the queue and sends it for processing to the class Message. The output Locked and Released Print Statements is not in the desired order.
EDIT
My expected answer should be: if it's in Producer that is add then Locked by Producer -> then add to Queue -> Lock Release. same way would be in consumer. But the operations shouldn't interleave i.e. once locked by producer is printed it shouldn't print locked by consumer and then release locks.