Friday, November 5, 2010

Thread Communication using wait() notify()

The following is a very simple example to demonstrate how multiple threads can communicate using the wait() notify () paradigms. The idea is to design a bounded Blocking Queue having a max size of 5. There will be two threads using the queue, where a thread will put 10 messages into the queue whereas the other will read the 10 messages. If the Queue has reached max size the Publisher thread has to wait till the queue has been read by the Consumer Thread. Similarly the Consumer thread will wait if the Queue is empty

BlockingQueue

public class BlockingQueue {

private Queue queue = new LinkedList();
String testingwait = new String();
private int capacity;

public BlockingQueue(int capacity) {
this.capacity = capacity;
}

public synchronized void put(T element) throws InterruptedException {
while(queue.size() == capacity) {
wait();
}

queue.add(element);
notifyAll();
}

public synchronized T take() throws InterruptedException {
while(queue.isEmpty()) {
wait();

}

T item = queue.remove();
notify();
return item;
}
}

MyThread


public class MyThread extends Thread {

BlockingQueue queue = null;
String threadname = null;


public MyThread(String threadname,BlockingQueue queue) {
super(threadname);
// TODO Auto-generated constructor stub
this.queue = queue;
this.threadname = threadname;
}



public void run() {
if(threadname.equals("PUTTINGTHREAD")){
for (int i = 0; i < 10; i++) {
try {
queue.put("value"+i);

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
for (int i = 0; i < 10; i++) {
try {
queue.take();

} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}



}

}





The Executable Class


public class TestThread {

public static void main(String[] args) {
BlockingQueue queue = new BlockingQueue(5);
Thread t = new MyThread("PUTTINGTHREAD",queue);
Thread t1 = new MyThread("TAKINGTHREAD",queue);
t.start();
t1.start();

}
}

No comments:

Post a Comment