I am about to take a test of Java. I have studied the examples of producers and consumers in the book. The book is only a program for a single consumer and a single producer. On the basis of this, I changed it to multiple producers and multiple consumers, unfortunately, the deadlock occurred, and I was puzzled. After studying the entire morning, the background finally found the cause through discussions with the teacher ------- notify () is to wake up a thread at random.
If the producer produces good things and the threads that have been randomly awakened are all producers, the deadlock will occur. Switching to yyall () can avoid deadlocks, but the efficiency will be reduced, but it is always much better than deadlock.
Program code:
Common repository class
Package threadlocktest;
/**
*
* @ Author DJ dance
*/
Public class common {
Private char ch;
Private Boolean available = false;
Synchronized char get (){
While (available = false ){
Try {
Wait ();
} Catch (interruptedexception e ){
}
}
Available = false;
Policyall ();
Return ch;
}
Synchronized void put (char newch ){
While (available = true ){
Try {
Wait ();
} Catch (interruptedexception e ){
}
}
Ch = newch;
Available = true;
Policyall ();
}
}
Consumer:
Package threadlocktest;
/**
*
* @ Author DJ dance
*/
Public class Consumer extends thread {
Private common comm;
Public consumer (Common thiscomm ){
This. Comm = thiscomm;
}
Public void run (){
Char C;
For (INT I = 0; I <5; I ++ ){
C = comm. Get ();
System. Out. println ("the data the consumer obtains is:" + C );
}
}
}
Producer:
Package threadlocktest;
/**
*
* @ Author DJ dance
*/
Public class producer extends thread {
Private common comm;
Public producer (Common thiscomm ){
Comm = thiscomm;
}
Public void run (){
Char C;
For (C = 'a'; C <= 'E'; C ++ ){
Comm. Put (c); system. Out. println ("the producer's data is:" + C );
}
}
}
Main Function
Code
Package threadlocktest;
/**
*
* @ Author DJ dance
*/
Public class main {
/**
* @ Param ARGs the command line arguments
*/
Public static void main (string [] ARGs ){
Common comm = new common ();
For (INT I = 0; I <100; I ++ ){
New producer (Comm). Start ();
New consumer (Comm). Start ();
}
}
}