Home » Core Java » Producer Consumer Problem Solution Example in Java

Producer Consumer Problem Solution Example in Java

This is a simple example of Producer and Consumer problem, where Producer created and puts data in a shared list but waits if the list is full. Similarly Consumer consumes data from the list but waits if the list is empty


import java.util.ArrayList;
import java.util.List;

class Pool{
	List list = new ArrayList();
	int MaxSize= 5;

	synchronized String getData() throws InterruptedException{
		if(list.isEmpty()){
			System.out.println("Get Data List is empty, wait please");
			wait();
			return null;
		}
		System.out.println("Get Data done: " + list.get(0));
		notifyAll();
		return list.remove(0); 
	}

	synchronized boolean setData(String str) throws InterruptedException{
		if(list.size()>=MaxSize){
			this.wait();
			System.out.println("Set Data , List is full please wait");
			return false;
		}else{
			System.out.println("Set Data , Data added > " + str);
		}
		list.add(str);
		notifyAll();
		return true;
	}

}
class Producer extends Thread{
	Pool pool;
	Producer(Pool pool){
		this.pool = pool;
	}

	@Override
	public void run() {
		for(int i=1; i<=70; i++){
			try {
				if(!this.pool.setData(i+"")){
					i--;
				}
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

}

class Consumer extends Thread{
	Pool pool;
	Consumer(Pool pool){
		this.pool = pool;
	}
	@Override
	public void run() {
		while(true){
			String i;
			try {
				i = this.pool.getData();
				Thread.sleep(2000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
}

public class ProducerConsumerTest {
	public static void main(String[] args){
			Pool pool = new Pool();
			Producer pro = new Producer(pool);
			Consumer con = new Consumer(pool);
			pro.start();
			con.start();
	}
}

Advertisements

2 Comments

  1. Neil says:

    Thank you for this very good working example. I was looking for a good example of producer and consumer code in java..just like that 🙂

  2. […] Producer Consumer Problem Solution Example in Java […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: