Search This Blog

Thursday 6 October 2016

Publisher And Subscriber Thread example using wait, notify & sleep methods

Publisher And Subscriber Thread example using wait, notify & sleep methods


Message.java

import java.util.Date;
class Message {
 
       String message = null;
 
       Message() {
message = new Date().toString();
}
 
       public void setMessage(String msg) {
message = msg;
}

public String getMessage() {
return message;
}
}

Publisher.java
import java.util.Vector;
class Publisher extends Runnable {

  static final int SIZE = 5;
  private Vector<Message> messages = null;
 
public Publisher() {
 
 messages = new Vector<Message>();

 }

    public void run() {
        try {
            while (true) {
                putMsg();
                sleep(1000);
            }
        } catch (InterruptedException exception) {
System.out.prinln("(Thread Interrupted......");
        }
    }

    private synchronized void putMsg() throws InterruptedException {
        while (messages.size() == SIZE) {
            wait();
        }
 
        //To prepare real time message usually will call services
        messages.addElement(new Message());
        System.out.println("put msg");
        notify();
    }

    public synchronized String getMsg() throws InterruptedException {
        notify();
        while (messages.size() == 0) {
            wait();
        }
        String tempMessage = (String) messages.firstElement();
        messages.removeElement(tempMessage);
        return tempMessage;
    }
}

Subscriber.java
class Subscriber extends Runnable {

    Publisher publisher= null;

    Subscriber(Publisher p) {
        publisher = p;
    }


    public void run() {
        try {
            while (true) {
                String msg = publisher.getMsg();
                System.out.println("Consumed message........." + msg);
                sleep(500);
            }
        } catch (InterruptedException exception) {
            System.out.prinln("(Thread Interrupted......");
        }
    }
}

PublisherAndSubscriberDemo.java
public class PublisherAndSubscriberDemo {

public static void main(String args[]) {
        Thread publisherThread = new Publisher();
        publisherThread.start();
        Thread  subscriberThread = new Subscriber(publisherThread);
subscriberThread.start();
    }

}

No comments:

Post a Comment