java中有简单的生产者/消费者功能。问题是只经过一个周期,都进入睡眠陷阱并且没有醒来。问题是消费者没有通知生产者使其清醒。在我的情况下,消费者不应该与生产者在同一个对象/类中。
我做错了吗?
这是我的实施:
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();
}
}
}
}
}