Simple implementation of reader Writer's problem with Java thread secure queue.

Source: Internet
Author: User

Common operating system textbooks use mutexes to synchronize the reader thread with the writer thread, but after JDK5 introduces the thread-safe queue, the problem becomes surprisingly simple.

Java.util.concurrent.ConcurrentLinkedQueue is a thread-safe non-blocking queue, it is very easy to think that the non-blocking queue when the thread needs to wait, it will not block the wait, but directly according to the situation to return.

Java.util.concurrent.LinkedBlockingQueue is a thread-safe blocking queue that can block threads in many cases, such as calling the Take () method when the queue is empty, by getting the object from the first team, or, if the object does not exist, The wait is blocked until a desirable object is awakened and the queue's first object is taken away. Similarly, this blocking queue also has a blocking method such as put (): If the queue is not available when the object is placed at the end of the line, block wait and know that the queue is available. The non-blocking queue does not have such a blocking method.


The following example is a simple example of using a non-blocking queue to implement a reader-writer problem:

Package Nonblockingqueueconpro;import Java.util.concurrent.concurrentlinkedqueue;public class MainThread {public static void Main (String args[]) {concurrentlinkedqueue<string> queue = new concurrentlinkedqueue<string> () ; for (int i = 0; i < 2; i++) {productor task = new Productor (queue); Thread t = new Thread (task, "producer thread" + i); T.start ();} for (int i = 0; i < 2; i++) {Consumer task = new Consumer (queue); Thread t = new Thread (task, "consumer thread" + i); T.start ();}}} Class Consumer implements Runnable {private concurrentlinkedqueue<string> queue;public Consumer ( Concurrentlinkedqueue<string> queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {try {thread.currentthread (). Sleep (+)} catch (Interruptedexception e) { E.printstacktrace ();} SYSTEM.OUT.PRINTLN ("Consumer--" + Queue.poll ())}}} Class Productor implements Runnable {private concurrentlinkedqueue<string> queue;public productor ( Concurrentlinkedqueue<string> queue) {this.queue = queue;} @overridepublic void Run () {while (true) {try {thread.currentthread (). Sleep (+)} catch (Interruptedexception e) { E.printstacktrace ();} String content = string.valueof (System.currenttimemillis ()); System.out.println ("producer ==>" + content); Queue.add (content);}}}



As you can see, the consumer thread may not be able to get the object (the queue is empty), then the poll () method returns NULL, and the resulting fragment runs as follows:

Consumer--  NULL consumer--  null producer ==>  1439301233285 producer ==>  1439301233284 consumer  -- 1439301233284 producer ==>  1439301234289 producer ==>  1439301234289 ...



In the case of blocking queue design, the consumer does not return null, and if the queue is empty, the consumer thread waits and the code is as follows:

Package Blockingqueueconpro;import Java.util.concurrent.linkedblockingqueue;public class Mainthread {public static void Main (String args[]) {linkedblockingqueue<string> queue = new linkedblockingqueue<string> (); for (int i = 0; I < 2; i++) {Productor task = new Productor (queue); Thread t = new Thread (task, "producer thread" + i); T.start ();} for (int i = 0; i < 2; i++) {Consumer task = new Consumer (queue); Thread t = new Thread (task, "consumer thread" + i); T.start ();}}} Class Productor implements Runnable {private linkedblockingqueue<string> queue;public productor ( Linkedblockingqueue<string> queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {try {thread.currentthread (). Sleep (+)} catch (Interruptedexception e) { E.printstacktrace ();} String content = string.valueof (System.currenttimemillis ()); System.out.println ("producer ==>" + content); Queue.add (content);}}} Class Consumer implements Runnable {private linkedblockingqueue<string> queue;public Consumer (LinkedBlockingqueue<string> queue) {this.queue = queue;} @Overridepublic void Run () {while (true) {try {thread.currentthread (). Sleep (+)} catch (Interruptedexception e) { E.printstacktrace ();} try {System.out.println ("consumer--" + queue.take ());} catch (Interruptedexception e) {e.printstacktrace ();}}}}



The results of the operation are as follows:

Producer ==>  1439301385710 producer ==>  1439301385710 Consumers--  1439301385710 consumers  -- 1439301385710 producer ==>  1439301386716 producer ==>  1439301386716 ...



Summary: In daily development, where thread safety is required, many of the classes below the Java.util.concurrent package can solve the problem, which is simpler and more secure than implementing object locks and synchronizations.

Simple implementation of reader Writer's problem with Java thread secure queue.

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.