Interview Questions

Output question 5.

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

65. Output question 5.

import java.util.ArrayList;
/* Producer is producing, Producer will allow consumer to
* consume only when 10 products have been produced (i.e. when production is over).
*/
class Producer implements Runnable{
ArrayList sharedQueue;

Producer(){
sharedQueue=new ArrayList();
}

@Override
public void run(){

synchronized (this) {
for(int i=1;i<=3;i++){ //Producer will produce 10 products
sharedQueue.add(i);
System.out.println("Producer is still Producing, Produced : "+i);

try{
Thread.sleep(1000);
}catch(InterruptedException e){e.printStackTrace();}

}
System.out.println("Production is over, consumer can consume.");
this.notify();
}
}
}

class Consumer extends Thread{
Producer prod;

Consumer(Producer obj){
prod=obj;
}

public void run(){
synchronized (this.prod) {

System.out.println("Consumer waiting for production to get over.");
try{
this.prod.wait();
}catch(InterruptedException e){e.printStackTrace();}

}


int productSize=this.prod.sharedQueue.size();
for(int i=0;i<productSize;i++)
System.out.println("Consumed : "+ this.prod.sharedQueue.remove(0) +" ");

}
}

public class MyClass {
public static void main(String args[]) throws InterruptedException{

Producer prod=new Producer();
Consumer cons=new Consumer(prod);

Thread prodThread=new Thread(prod,"prodThread");
Thread consThread=new Thread(cons,"consThread");


consThread.start();
Thread.sleep(100); //minor delay.
prodThread.start();

}
}

Answer.
Because of minor delay delay consThread surely started before producer thread.
"Consumer waiting for production to get over." printed first
than producer produced
than "Production is over, consumer can consume."
than consumer consumed.


The above program is classical example of how to solve Consumer Producer problem by using wait() and notify() methods.

/*OUTPUT
Consumer waiting for production to get over.
Producer is still Producing, Produced : 1
Producer is still Producing, Produced : 2
Producer is still Producing, Produced : 3
Production is over, consumer can consume.
Consumed : 1
Consumed : 2
Consumed : 3
*/

(Continued on next question...)

Other Interview Questions