HTML Java

Java Producercon


Producer Consumer Problem using waiting and notify

If producer produce 5 items and its limit is 5 after producing items with its max capacity and then its come in waiting state and comsumer and check if items is > 0 then its start consming after consuming all the items it will come in waiting state.this program will run infinite time because as producer creates item comsumer consume and again producer produce and consumer consume.

Example:

package DemoThreads
import java.util.ArrayList;
import java.util.List;
class Producer extends Thread{
List list;
public Producer(List list) {
this.list =list;
}
public void run() {
try {
synchronized(list) {
while(true) {
if(list.size()>0) {
list.wait();
}
else
produceItem();
}
}
}catch(InterruptedException e) {
e.printStackTrace();
}
}
private void produceItem() throws InterruptedException{
for(int i=1;i<=5;i++) {
Thread.sleep(1000);
list.add(i);
System.out.println("Added Element in list by producer = "+i);
}
list.notifyAll();
}
}
}

Or also you can do like this

Example

class Consumer extends Thread{
List list;
public Consumer(List list) {
this.list =list;
}
public void run() {
try {
synchronized(list) {
while(true) {
if(list.size()==0) {
list.wait();
}
else
consumeItem();
}
}
}catch(InterruptedException e) {
e.printStackTrace();
}
}
private void consumeItem() throws InterruptedException{
while(!list.isEmpty()) {
Thread.sleep(1000);
System.out.println("remove element from the list by consumer="+list.remove(0));
}
list.notifyAll();
}
}

Example

public class ProducerConsumer {
public static void main(String args[]) {
List list = new ArrayList();
Producer producer = new Producer(list);
Consumer consumer = new Consumer(list);
producer.start();
consumer.start();
}
}

Output

Added Element in list by producer = 1
Added Element in list by producer = 2
Added Element in list by producer = 3
Added Element in list by producer = 4
Added Element in list by producer = 5
remove element from the list by consumer=1
remove element from the list by consumer=2
remove element from the list by consumer=3
remove element from the list by consumer=4
remove element from the list by consumer=5