Java multithreading producer consumer, java multithreading producer

Source: Internet
Author: User

Java multithreading producer consumer, java multithreading producer

Producer and consumer instances:

Product Type:
/**
* Product type
*
*/
Public class Goods {
Final int MAX_NUMBER = 30; // maximum number
Final int MIN_NUMBER = 0; // minimum number
Private int number;
Public Goods (int number ){
Super ();
This. number = number;
}
Public synchronized int getNumber (){
Return number;
}
// Add
Public void addNumber () throws InterruptedException {
If (number> = MAX_NUMBER ){
Wait ();
}
Synchronized (this) {// Synchronous Code Block
This. number = number + 1;
System. out. println ("the number of products produced by the producer is:" + number );
}
Policyall ();
}
// Reduce
Public void sumNumber () throws InterruptedException {
If (number <= MIN_NUMBER ){
Wait ();
}
Synchronized (this ){
This. number = number-1;
System. out. println ("the number of items consumed by the consumer is:" + number );
}
Policyall ();
}
}

Test class:

Package book_14.synch;

Public class Test {

Public static void main (String [] args ){
// Create an object
Goods good = new Goods (20); // The starting item quantity is set to 20.

While (true ){
// Producer
Runnable r1 = ()-> {
Try {
While (true ){
Good. addNumber ();
// Thread. sleep (10 );
}
} Catch (Exception e ){
// TODO: handle exception
}
};
Thread t1 = new Thread (r1 );
T1.start ();
// Consumer
Runnable r2 = ()-> {
Try {
While (true ){
Good. sumNumber ();
// Thread. sleep (10 );
}
} Catch (Exception e ){
// TODO: handle exception
}
};
Thread t2 = new Thread (r2 );
T2.start ();
}

}

}

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.