Difference between queue and blockingqueue in Java

Source: Internet
Author: User
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 ();

}

}

Related Article

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.