class Q {
volatile boolean valueSet = false;
volatile int n;
synchronized int get () {
if ( !valueSet ) {
try {
wait();
} catch ( InterruptedException e ) {
System.out.println( "InterruptedException caught" );
}
}
System.out.println( "Got: " + n );
valueSet = false;
notify();
return n;
}
synchronized void put ( int n ) {
if ( valueSet ) {
try {
wait();
} catch ( InterruptedException e ) {
System.out.println( "InterruptedException caught" );
}
}
this.n = n;
valueSet = true;
System.out.println( "Put: " + n );
notify();
}
}
class Producer
implements Runnable {
Q q;
Producer ( Q q ) {
this.q = q;
new Thread( this, "Producer" ).start();
}
public void run () {
int i = 0;
while ( true ) {
q.put( i++ );
}
}
}
class Consumer
implements Runnable {
Q q;
Consumer ( Q q ) {
this.q = q;
new Thread( this, "Consumer" ).start();
}
public void run () {
while ( true ) {
q.get();
}
}
}
class PCFixed {
public static void main ( String args[] ) {
Q q = new Q();
new Producer( q );
new Consumer( q );
System.out.println( "Press Control-C to stop." );
}
}
我无法理解这是如何工作的。以这个流程为例。Producer进入put方法,调用notify()。如果消费者还没有调用 wait() 怎么办?还有,一旦producer调用notify(),在producer还没有放开monitor的情况下,consumer怎么进入get()方法呢?请帮帮我。