threads
Thread communication using Queue example
This is an example of how to achieve a queue communication between two Threads. The example is described in short:
- We have created a class,
PrepProduct
that implements the Runnable and has a BlockingQueue of Strings. It overrides therun()
API method of the Runnable where
it puts two elements to the BlockingQueue, waiting if necessary for space to become available, withput(String e)
API method of BlockingQueue. - We have also created a class
Production
that implements the Runnable, and also has a BlockingQueue of Strings. It overrides therun()
API method of the Runnable where it retrieves and removes the head of this queue, waiting if necessary until an element becomes available, usingtake()
API method of BlockingQueue. - We create a new BlockingQueue of Strings and two Threads initialized with the two Runnable objects created above. We call their
start()
API methods to begin their execution and then theirjoin()
API method that waits for each thread to die. The first thread puts two strings in the BlockingQueue and then the other thread retrieves them from the queue. This is how the communication is accomplished through the threads.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; class PrepProduct implements Runnable { BlockingQueue<String> blQueue; PrepProduct(BlockingQueue<String> bqueu) { blQueue = bqueu; } @Override public void run() { try { blQueue.put("1"); blQueue.put("end"); } catch (Exception e) { e.printStackTrace(); } } } class Production implements Runnable { private final BlockingQueue<String> queue; Production(BlockingQueue<String> bqueue) { queue = bqueue; } @Override public void run() { try { String value = queue.take(); while (!value.equals("end")) { value = queue.take(); System.out.println(value); } } catch (Exception e) { System.out.println(Thread.currentThread().getName() + " " + e.getMessage()); } } } public class QueueCommunication { public static void main(String[] args) throws Exception { BlockingQueue<String> q = new LinkedBlockingQueue<String>(); Thread prep = new Thread(new PrepProduct(q)); Thread prod = new Thread(new Production(q)); prep.start(); prod.start(); prep.join(); prod.join(); } }
Output:
end
This was an example of how to achieve a queue communication between two threads in Java.