0

There are simple producer / consumer functions in java. Problem is after only one cycle, both get into the sleep trap and doesn't get awake. The issue is notify from consumer doesn't reach to producer to make it awake. In my case the consumer should not be in the same object/class as producer is.

Did i do something wrong?

Here is my implementation:

package test.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
boolean isProduced = false;
Producer producer;
int theValue;
Random r = new Random();

public synchronized void consumer()
{
        if (!isProduced) {
            try {
                System.out.println("WAIT Consumer");
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Consumed: " + theValue);
        isProduced = false;
        this.notify();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    producer = new Producer();
    producer.start();

    new  Thread( new Runnable() {
        public void run() {
            while(true) {
                consumer();
            }
        }
    }).start();
}


// ----------------PRODUCER CLASS------------------------
protected class Producer implements Runnable {

    protected Thread thread;

    protected void start() {
        thread = new Thread(this, "Producer");
        thread.start();
    }

    //@Override
    public void run() {

        synchronized (this) {
            while (thread != null) {

                if (isProduced) {
                    try {
                        System.out.println("WAIT Producer");
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                theValue = r.nextInt(10);
                System.out.println("Produced: " + theValue);
                isProduced = true;
                this.notify();
            }
        }
    }
}
}
A. Fasih
  • 73
  • 1
  • 10

0 Answers0