Untitled

mail@pastecode.io avatar
unknown
plain_text
20 days ago
2.5 kB
5
Indexable
Never
import java.util.*;
class Producer implements Runnable {
	NotificationQueue notificationQueue;
	int counter = 0;
	Producer(NotificationQueue notificationQueue) {
    	this.notificationQueue = notificationQueue;
    }
	public void run() {
    	while(true) {
          if (notificationQueue.QUEUE_CAPACITY > notificationQueue.getSize()) {
              System.out.println(notificationQueue
              .addMessage("message added successully " + counter++));
          }
          try {
              Thread.sleep(400);
          } catch(Exception exception) {
              System.out.println("Exception occurred " + exception);
          }
        }
    }

}

class Consumer implements Runnable {
	NotificationQueue notificationQueue;
	Consumer(NotificationQueue notificationQueue) {
    	this.notificationQueue = notificationQueue;
    }
	public void run() {

    	while(true) {
          if(notificationQueue.getSize() > 0) {
              System.out.println("message consumed successfully " + notificationQueue.getMessage());
          }
                  try {
              Thread.sleep(1000);
          } catch(Exception exception) {
              System.out.println("Exception occurred " + exception);
         }
        }
        

    }
}

class NotificationQueue {
	private static NotificationQueue notificationQueue;
    private static Queue<String> queue;
    public static int QUEUE_CAPACITY = 10;
    
    private NotificationQueue() {
		queue = new LinkedList<>();
    }
    
    public static NotificationQueue getInstance() {
    	if (notificationQueue == null) {
        	return new NotificationQueue();
        }
        return notificationQueue;
    }
    
    public int getSize() {
    	return queue.size();
    }
    
    public String addMessage(String message) {
    	synchronized(NotificationQueue.class) {
        	queue.add(message);
        }
        return message;
    }
    
    public String getMessage() {
    	synchronized(NotificationQueue.class) {
        	return queue.remove();
        }
    }
    
}




public class Main {
  public static void main(String[] args) {
  	NotificationQueue notificationQueue = NotificationQueue.getInstance();
    Thread thread1 = new Thread(new Producer(notificationQueue));
    thread1.start();
    Thread thread2 = new Thread(new Consumer(notificationQueue));
    thread2.start();
    
  	
  }
}
Leave a Comment