1. blockingqueue: two additional operations are supported. These two operations are: waiting for the queue to become non-empty when retrieving elements, and waiting for space to become available when storing elements.
2. blockingqueue does not accept null elements.
3. blockingqueue can be a limited capacity.
4. blockingqueue implementation is thread-safe. Queue is NOT thread-safe. Therefore, blockingqueue can be used for producer-user queues.
Based on an example of API modification, you can modify your own experience to use blockingqueue.
Package test;
Import java. util. Concurrent. arrayblockingqueue;
Import java. util. Concurrent. blockingqueue;
/**
* Producer
* @ Author wasw100
*/
Class producer implements runnable {
Private Final blockingqueue queue;
Producer (blockingqueue q ){
Queue = Q;
}
Public void run (){
Try {
For (INT I = 0; I <3; I ++ ){
Queue. Put (produce ());
System. Out. println ("after production:" + queue. Peek ());
}
} Catch (interruptedexception ex ){
Ex. printstacktrace ();
}
}
Character produce (){
Char c = (char) (math. Random () * 26 + 'A ');
System. Out. println ("before production:" + C );
Return C;
}
}
/**
* Consumer
* @ Author wasw100
*/
Class consumer implements runnable {
Private Final blockingqueue queue;
Consumer (blockingqueue q ){
Queue = Q;
}
Public void run (){
Try {
While (true ){
Consume (queue. Take ());
// Thread. Sleep (100 );
}
} Catch (interruptedexception ex ){
Ex. printstacktrace ();
}
}
Void consume (character c ){
System. Out. println ("Consumption:" + C );
}
}
/**
* One producer and two consumers
*
* @ Author wasw100
*/
Class setup {
Public static void main (string [] ARGs ){
Blockingqueue q = new arrayblockingqueue (1 );
Producer P = new producer (Q );
Consumer C1 = new consumer (Q );
Consumer C2 = new consumer (Q );
New thread (P). Start ();
New thread (C1). Start ();
New thread (C2). Start ();
}
}