Java thread (additional article): Blocking queue blockingqueue

Source: Internet
Author: User

I haven't written an article for a long time. During this time, my work was messy. I just moved my house from my own house to the building last week, improving the quality of life. Haha! However, my wallet was stolen on the bus last night, and a bicycle was lost some time ago. I had to sigh that there were so many pickpockets in Beijing that no one had to handle them yet. To put it bluntly, during this period of time, my work mainly improved the company's schedulers, schedulers scheduled thread pools to execute tasks, producer production tasks, and consumers to consume tasks. In this case, a task queue is required, the producer inserts a task into the queue, and the consumer extracts the task from the queue for execution. The queue is implemented by blockingqueue In the scheduler. Then, let's look at the principle and method of blockingqueue.

Blockingqueue has four conditions: throwing an exception, returning special values, blocking, and timeout. The following table summarizes these methods:

  Throw an exception Special Value Blocking Timeout
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Check element() peek() Unavailable Unavailable

Blockingqueue is an interface and has the following implementation classes:

1. arrayblockqueue: A Bounded blocking queue supported by arrays. This queue sorts the elements according to the FIFO principle. The size of the object to be created must be clear, just like an array.

2. Define blockqueue: a blocking queue that can change the size. This queue sorts the elements according to the FIFO principle. If the size of the created object is not specified, the default value is integer. max_value. The throughput of the link queue is usually higher than that of the array-Based Queue, but its predictable performance is lower in most concurrent applications.

3. priorityblockingqueue: similar to linkedblockingqueue. However, the sorting of objects contained in priorityblockingqueue is determined based on the natural sorting order of objects or the comparator in the constructor.

4. synchronousqueue: Synchronous queue. The synchronization queue does not have any capacity. Each insert must wait for another thread to be removed, and vice versa.

The following uses arrayblockqueue to implement the producer consumer/payer mode previously implemented. The Code is as follows:

/** Defines a plate class, which can hold eggs and take eggs */public class bigplate {/** to hold eggs on the plate, the size is 5 */private blockingqueue <Object> eggs = new arrayblockingqueue <Object> (5);/** put eggs */Public void putegg (Object egg) {try {eggs. put (EGG); // put an egg at the end of the plate. If the plate is full, the current thread is blocked} catch (interruptedexception e) {e. printstacktrace ();} system. out. println ("put eggs");}/** get eggs */public object getegg () {object egg = NULL; try {egg = eggs. take (); // get an egg from the plate. If the plate is empty, the current thread is blocked.} catch (interruptedexception e) {e. printstacktrace ();} system. out. println ("get eggs"); Return egg;}/** put eggs thread */static class addthread extends thread {private bigplate; private object egg = new object (); public addthread (bigplate plate) {This. plate = plate;} public void run () {plate. putegg (EGG) ;}}/** take the egg thread */static class getthread extends thread {private bigplate plate; Public getthread (bigplate plate) {This. plate = plate;} public void run () {plate. getegg () ;}} public static void main (string [] ARGs) {bigplate plate = new bigplate (); // start 10 put eggs threads for (INT I = 0; I <10; I ++) {New thread (New addthread (plate )). start () ;}// start 10 more egg threads for (INT I = 0; I <10; I ++) {New thread (New getthread (plate )). start ();}}}

Execution result:

Put the eggs, put the eggs, get the eggs, get the eggs, put the eggs, put the eggs, get the eggs, get the eggs

From the results, we started 10 put eggs threads and 10 get eggs threads. Five put eggs into five threads were successfully executed, to 6th, and we found that the plate was full and blocked, switch to the egg fetch thread for execution, and the producer/consumer mode is successfully implemented. The Java. util. Concurrent package is a powerful package!

This article is from: Gao Shuang | coder, original address: http://blog.csdn.net/ghsau/article/details/8108292.

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.