Basic Java Tutorial: Multithreading Basics (3)-blocking queues quickly starting to introduce problems
Producer-consumer issues are a classic problem in threading models: producers and consumers share the same storage space during the same time period , producing data from the producer to the space, while consumers take the data away .
Simulation Scenarios
Here we implement the following scenarios for the production-consumption model:
Producers are constantly alternately producing two sets of data "name--1--> content--1", "Name--2--> content--2", where "name--1" and "name--2" simulate the name of the data, "content--1" and "Content--2" simulation for The content of the data .
Due to the uncertainty involved in threading the program, the following issues may occur:
1. Assuming that the producer Line Cheng Gang adds the name of the data to the data storage space and does not include the content of the information, the program switches to the consumer thread, and the consumer thread links the name of the information to the content of the previous message;
2. Producers produce a number of data, consumers can access the data, or, after the consumers have completed the data, they have not yet waited for the producers to put in the new data, and then repeated the data that has been taken.
Through analysis we know:
The first problem can be resolved by synchronization , and the second problem requires the use of thread communication . After the producer thread puts in the data, notifies the consumer thread to take out the data, the consumer thread takes out the data, notifies the producer of the thread production data, which is implemented by the WAIT\NOTIGY mechanism.
Java Code Definition Information class
Package Thread;public class Info {private String name = "Name"; Private String content = "content"; Sets the flag bit to use for thread communication private Boolean flag =true; /** * Set message, use thread synchronization here * @param name * @param content */public synchronized void set (String name,string C Ontent) {while (!flag) {try {super.wait (); } catch (Interruptedexception e) {e.printstacktrace (); }} This.name=name; Set name try {thread.sleep (1000); } catch (Interruptedexception e) {e.printstacktrace (); } this.content=content; Set content flag =false; Set the flag bit, indicating that production is now stopped, can take away! Public synchronized void get () {while (flag) {try {super.wait ()}; } catch (Interruptedexception e) {e.printstacktrace (); }} try {Thread.Sleep (300); } catch (InterrUptedexception e) {e.printstacktrace (); } System.out.println (name + "-+" + content); Flag = true; Change the sign, indicate can produce super.notify (); }}
Define Producer
public class Producer implements Runnable { private Info info=null; Public Producer (Info info) { this.info=info; } @Override public Void Run () { Boolean flag = true; Defines the tag bit for (int i=0;i<10;i++) { if (flag) { this.info.set ("Name--1", "Content--1"); Set name flag = false; } else{ this.info.set ("Name--2", "Content--2"); Set name flag = True;}}}
Define Consumer
public class Consumer implements Runnable { private Info info = null; Public Consumer (Info info) { this.info = info; } public void Run () {for (int i=0;i<10;i++) { this.info.get ()} } public static void Main (string[] args) { info info = new Info ();//Instantiate Info object Producer Pro = new Producer (info) ; Producer Consumer con = new Consumer (info);//Consumer new Thread (PRO). Start (); After starting the producer thread, start the consumer thread try{ thread.sleep; } catch (Interruptedexception e) { e.printstacktrace (); } New Thread (Con). Start (); }}
Using blocking queues to implement the same functionality introduced
BlockingQueue
Any effective producer-consumer problem solution is achieved by controlling the call of the producer put () method (the production resource) and the consumer Take () method (consumption resource), and once you implement blocking control of the method, you will solve the problem. Java BlockingQueue
controls the invocation of these methods by providing out-of-the-box support (one thread creates resources and another consumes resources). java.util.concurrent
the interface under the package BlockingQueue
is a thread-safe queue that can be used to access objects .
Blockingqueue is a data structure that supports one thread to the inside of a resource, and another thread to fetch resources from it. This is what is needed to solve the problem of producer consumers, so let's start solving the problem.
Java code Message Class
public class Infoplus { private String name = "Name"; Private String content = "content"; Public Infoplus (string name, string content) { this.name = name; this.content = content; } Public String GetName () { return name; } public void SetName (String name) { this.name = name; } Public String getcontent () { return content; } public void SetContent (String content) { this.content = content; } @Override public String toString () { return ' infoplus{' + ' name= ' + name + ' \ ' + ', content= ' + con Tent + ' \ ' + '} ';} }
Producers
Import Java.util.concurrent.blockingqueue;public class Producerplus implements Runnable { private blockingqueue <InfoPlus> queue; Public Producerplus (blockingqueue<infoplus> queue) { this.queue = queue; } @Override public Void Run () {for (int i=0;i<10;i++) { try { thread.sleep (); Queue.put (New Infoplus ("name" +i, "Content" +i)); catch (Interruptedexception e) { e.printstacktrace ();}}}}
Consumers
Import Java.util.concurrent.blockingqueue;import Java.util.concurrent.linkedblockingdeque;public class Consumerplus implements runnable{private blockingqueue<infoplus> queue; Public Consumerplus (blockingqueue<infoplus> queue) {this.queue = queue; public void Run () {while (true) {try {System.out.println (This.queue.take ())}; } catch (Interruptedexception e) {e.printstacktrace (); }}} public static void Main (string[] args) {blockingqueue<infoplus> blockingqueue = new Linke Dblockingdeque<> (); Producerplus producerplus = new Producerplus (blockingqueue); Consumerplus consumerplus = new Consumerplus (blockingqueue); Consumerplus ConsumerPlus1 = new Consumerplus (blockingqueue); New Thread (Producerplus). Start (); New Thread (Consumerplus). Start (); New Thread (CONSUMERPLUS1). Start (); }}
Basic Java Tutorial: Multithreading Basics (3)-blocking queues