ayush nigam
ayush nigam

Reputation: 177

Use of Notify Method in Multithreading

I am learning multithreading.

I tried to implement producer consumer problem in Java.Its working fine. But if i remove notify call the program goes into a deadlock state.Why?

Its going on deadlock when size of queue becomes 0.Ideally when size becomes 0,wait should be called inside consumer and producer should started working.

import java.io.*;
import java.util.*;

class Consumer implements Runnable{

Queue<Integer> q;
int n;

public void run() {

    while(true){
        synchronized (q) {
        while(q.size()==0){
            try {
      System.out.println("q.size="+q.size());
                q.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("item consumed="+q.poll());
        q.notify();
        try {
            Thread.sleep((int)(Math.random() * 100));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
  }
}
Consumer(Queue<Integer> queue,int n){
    q=queue;
    this.n=n;
}

}

class Producer implements Runnable{

Queue<Integer> q;
int n;


public void run() {
int x=1;
    while(true){

        synchronized (q) {
        while(q.size()==n){

                try {
                    q.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
            System.out.println("item produced="+x+" q.size="+q.size());
            q.add(x++);
            q.notify();
            try {
                Thread.sleep((int)(Math.random() * 100));
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

    }
 }
}

Producer(Queue<Integer> queue,int n){
    q=queue;
    this.n=n;
  }
}
public class App
{
public static void main( String[] args ) throws InterruptedException
{
    int n=100;
    Queue<Integer> q=new LinkedList<Integer>();
    Thread t1=new Thread(new Producer(q, n));
    Thread t2=new Thread(new Consumer(q, n));

    t1.start();
    t2.start();

    t1.join();
    t2.join();
  }
}

Upvotes: 0

Views: 24

Answers (1)

gati sahu
gati sahu

Reputation: 2626

you required notify because when one thread is on wait state because queue is empty or full come to running state if some other thread notify after putting if queue is empty and taking queue is full. put q.wait(10); so your code will not go on deadlock because after time it will check while loop condition. It is always best practice to use notify in above usecase

Upvotes: 1

Related Questions