Producer-consumption patterns, which typically have two types of threads, that is, several producer threads and several consumer threads. Producer threads are responsible for submitting user requests, and consumer threads are responsible for dealing specifically with the tasks submitted by the producer. The two communicate with each other through a shared memory buffer.
first, the architectural pattern diagram:
Class Diagram:
Producer: Submits user request, extracts user task, and loads into memory buffer;
Consumer: extracting and processing tasks in the memory buffer;
Memory buffers: Caching of tasks or data submitted by a producer for use by consumers;
Task: The data structure submitted by the producer to the memory buffer;
Main: Use client of producer and consumer.
Second, the code implementation of a producer-consumer model for the parallel calculation of integer squares:
(1) Producer producer Thread:
[Java]View Plain copy print? package producerconsumer; import java.util.random; import java.util.concurrent.blockingqueue; import java.util.concurrent.timeunit; Import java.util.concurrent.atomic.AtomicInteger; public class producer implements Runnable{ // Volatile decorated member variables are forced to reread the value of the member variable from shared memory each time it is accessed by the thread. //Also, when a member variable is changed, the thread is forced to write the change value back to shared memory. //So at any time, two different threads always see the same value for a member variable. private volatile boolean isRunning= true; //memory buffers private blockingqueue<pcdata> queue; //Total, atomic operation private static AtomicInteger count = new Atomicinteger (); private static final int sleeptime=1000; public producer (Blockingqueue<pcdata> queue) { this.queue = queue; } @Override Public void run () { pcdata data =null; Random r = new Random (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("start producer id = "+ thread .currentthread () getId ()); try{ while (isRunning) { Thread.Sleep (R.nextint (sleeptime)); //Construction Task Data data= new pcdata (Count.incrementandget ()); System.out.println ("data is put into queue "); //submit data to buffer if (!queue.offer (data,2,timeunit.seconds)) { system.out.println ("faile to put data: " + data); } } }catch (interruptedexception e) { e.printstacktrace (); thread.currentthread () interrupt (); } } public void stop () { isRunning=false; } }
(2) Consumer consumer thread:
[Java]View Plain copy print? package producerconsumer; import java.text.messageformat; Import java.util.Random; import java.util.concurrent.blockingqueue; public class consumer implements runnable { //Buffer private BlockingQueue<PCData> queue; private static final int SLEEPTIME=1000; public Consumer (Blockingqueue<pcdata> queue) { this.queue = queue; } @Override &nbsP; public void run () { system.out.println ("start consumer id= " + thread .currentthread (). GetId ()); random r = new random (); try { //Extraction Task while (true) { PCData data= Queue.take (); &nbsP; if (null!= data) { //Compute Squared int re= data.getdata () *data.getdata (); system.out.println (Messageformat.format ("{0}*{1}={2}", data.getdata (), Data.getdata (),re ); thread.sleep (R.nextint (sleeptime)); } } } catch (interruptedexception e) { e.printstacktrace (); thread.currentthread (). Interrupt (); } } }
(3) Pcdata shared data Model:[Java]View Plain copy print? package producerconsumer; public final class pcdata { private final int intData; public pcdata (int d) { intData=d; } public pcdata (string d) { intdata=integer.valueof (d); } public int getdata () { return intData; &NBSP;&NBSP;&Nbsp; } @Override public string tostring () { return "Data:" + intdata ; } }
(4) Main function:[Java]View Plain copy print? package producerconsumer; import java.util.concurrent.blockingqueue; import java.util.concurrent.executor; import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.linkedblockingdeque; public class main { /** * @param args */ public static void main ( String[] args) throws InterruptedException{ //Build Buffer blockingqueue<pcdata > queue = new LinkedBlockingDeque<PCData> (a); //set up producer Producer producer1 = New producer (queue); producer producer2 = new producer (queue); producer producer3 = new producer (queue);