Package com. jzm. thread;
Class q {
Int N;
Boolean valueset = false;
Synchronized int get (){
// The value has not been put. Wait for the put value.
If (! Valueset ){
Try {
Wait ();
} Catch (interruptedexception e ){
System. Out. println ("interrupt caught ");
}
}
System. Out. println ("got:" + n );
Valueset = false;
Notify ();
Return N;
}
Synchronized void put (int n ){
// Put the value, wait for the got to take the value, and then place the value
If (valueset ){
Try {
Wait ();
} Catch (interruptedexception e ){
System. Out. println ("interrupt caught ");
}
}
This. n = N;
System. Out. println ("put:" + n );
Valueset = true;
Notify ();
}
}
Class producer implements runnable {
Q;
Public producer (Q ){
This. q = Q;
New thread (this, "producer"). Start ();
}
@ Override
Public void run (){
Int I = 0;
While (true ){
Q. Put (I ++ );
}
}
}
Class consumer implements runnable {
Q;
Public consumer (Q ){
This. q = Q;
New thread (this, "consumer"). Start ();
}
@ Override
Public void run (){
// Todo auto-generated method stub
Int I = 0;
While (true ){
Q. Get ();
}
}
}
Public class customerproduct {
Public static void main (string [] ARGs ){
Q = new Q ();
New producer (Q );
New consumer (Q );
System. Out. println ("Press contro_c to stop ");
}
}