开发者

Android(Java) Producer/Consumer with Timer

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 prod开发者_JAVA技巧ucer 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.


you should use notifyAll(). notify does not gaurantee which thread is notified. Also check hat empty is actually synchronized (i.e. is owned by the status class where get and put reside.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜