I am testing a simple producer/ consumer example in android this is what i’m doing.
I have two EditText boxes, one being a producer and the other a consumer. The app also has a single button once this button is pressed two timers start and the producer produces while the consumer consumes. Here is my code:
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Timer producerTimer = new Timer();
producerTimer .schedule(new TimerTask(){
@Override
public void run(){
producer();
}
},100, 300);
Timer consumerTimer = new Timer();
consumerTimer .schedule(new TimerTask(){
@Override
public void run(){
consumer();
}
},100, 300);
}
});
}
Now for the other methods:
public void producer(){
this.runOnUiThread(producer_Tick);
}
public void consumer(){
this.runOnUiThread(consumer_Tick2);
}
private Runnable producer_Tick = new Runnable(){
public void run(){
put(i++);
}
};
private Runnable consumer_Tick= new Runnable(){
public void run(){
int result = get();
consumerBox.append(Integer.toString(result) + "\n");
}
};
Here are my Synchronized methods:
public synchronized void put(int val){
if (!empty){
try{
wait();
}catch (InterruptedException e) {Log.d(TAG,"Error Putting");}
}
producerBox.append(Integer.toString(val) + "\n");
empty = false;
buffer=val;
notify();
}
public synchronized int get(){
if (empty){
try{
wait();
}catch (InterruptedException e) {Log.d(TAG,"Error getting");}
}
empty = true;
notify();
return buffer;
}
This program runs to random points all the time. Sometimes for a couple of minuites it runs fine where consumer reads from producer etc.. However, everytime, at some point, the program will just freeze at producer and consumer at a certain value (random each time). Does anyone see a problem with the above code?
You should use a blocking queue to communicate between producer-consumer threads in more efficient and easy to understand way.