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