Tuesday, April 18, 2006

Producer Consumer Problem

First Create a package learning
then

create following java files
1) Shared Object
2) Producer
3) Consumer
4) Main Class

-------------------------------------------------------------------------------
package learning;

/**
*
* @author AshwinK
*/
public class Shared {

/** Creates a new instance of Shared */
public Shared() {
}

synchronized void setSharedChar(char c){
if(!writable){
try{
wait();
}catch(InterruptedException e){

}
}
System.out.println(c+"---Produced by Producer");
this.c = c;
writable = false;
notify();
}


synchronized char getSharedChar(){
if(writable){
try{
wait();
}catch(InterruptedException e){

}
}

writable = true;
System.out.println(c+"---Consumed by Consumer");
notify();
return c;
}

private char c = '\u0000';
private boolean writable = true;

}
-------------------------------------------------------------------------------
Now create producer

-------------------------------------------------------------------------------
package learning;

/**
*
* @author AshwinK
*/
public class Producer extends Thread{

private Shared s;
/** Creates a new instance of Producer */
public Producer(Shared s) {
this.s = s;
}

public void run(){
for(char ch = 'A'; ch <= 'Z';ch++){
try{
Thread.sleep((int)(Math.random()*2000));
}catch(InterruptedException e){

}
s.setSharedChar(ch);

}
}

}

-------------------------------------------------------------------------------
Now Create Consumer
-------------------------------------------------------------------------------
package learning;

/**
*
* @author AshwinK
*/
public class Consumer extends Thread{
private Shared s;
/** Creates a new instance of Consumer */
public Consumer(Shared s){
this.s = s;
}

public void run(){
char ch;
do{
try{
Thread.sleep((int)(Math.random()*1000));
}catch(InterruptedException e){

}
ch = s.getSharedChar();

}while(ch!='Z');
}
}
-------------------------------------------------------------------------------


Create Main
-------------------------------------------------------------------------------

package learning;

/**
*
* @author AshwinK
*/
public class Main {

/** Creates a new instance of Main */
public Main() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Shared s = new Shared();
new Producer(s).start();
new Consumer(s).start();
}

}
-------------------------------------------------------------------------------

You need basic understanding of thread's to understand this post.I'll heading with threading tutorial from tommorrow

No comments: