Java simulated producer consumer issues

Source: Internet
Author: User

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 ");
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.