A comprehensive example that demonstrates concurrent read and write of a finite-length character sequence buffer, or producer-consumer issues. The point of omission, please indicate ^_^
/** * Pcproblem: * Simulation Producer-consumer problem, producer produces character and writes character sequence buffer, consumer takes away character from buffer * * @author shuqin1984 2011-08-05 * * * Package Threadprogramming.basic.simulation;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;public class Pcproblem {public static void main ( String[] args) {System.out.println ("----Thread main starts up----");//simulation Producer-Consumer task Sharedcharbuffer Sharedbuffer = New Sharedcharbuffer (10); Executorservice es = Executors.newcachedthreadpool (); for (int i=1; I <=; i++) {Es.execute (new Producerthread (I, Shar Edbuffer)); Es.execute (New Consumerthread (I, Sharedbuffer));} Es.shutdown ();//Run 5 seconds after terminating the simulated try {TimeUnit.SECONDS.sleep (5);} catch (Interruptedexception e) {e.printstacktrace ();} Producerthread.cancel (); Consumerthread.cancel (); Es.shutdownnow (); System.out.println ("Time to is over.");}}
Producer: Producer.java
/** * Producerthread: Producer thread */package Threadprogramming.basic.simulation;import java.util.random;import Java.util.concurrent.timeunit;public class Producerthread extends Thread {private static String str = "ABC1DEFG2HIJK3LMN O4pqrs5tuvwx6yz "+" ab7cdef8ghijk9lmno0pqr_stu*vwxyz ";p rivate static volatile Boolean endflag = false;private final int Id;private sharedcharbuffer buffer;public producerthread (int id, sharedcharbuffer buffer) {this.id = Id;this.buffer = buf Fer;} public static void Cancel () {Endflag = true;} public Boolean isCanceled () {return endflag = = true;} /** * Producer task: As long as the task is not canceled and the buffer is not satisfied, go to the buffer character */public void run () {while (!iscanceled () &&! Thread.interrupted ()) {synchronized (buffer) {while (Buffer.isfull ()) {//buffer is full, producer must wait for try {buffer.wait ();} catch (I Nterruptedexception e) {System.out.println (this + "interrupted.");}} char ch = produce (); System.out.println (Timeindicator.getcurrtime () + ": \ T" + this + "prepare write buffer:" + ch); buffer.write (CH); System.out.println (TimeindiCator.getcurrtime () + ": \ T" + this + ": \t\t\t" + buffer); Buffer.notifyall ();} try {TimeUnit.MILLISECONDS.sleep;} catch (Interruptedexception e) {System.out.println (this + "interrupted.");}} System.out.println ("Exit from:" + This);} public char Produce () {Random rand = new Random (); return Str.charat (Rand.nextint (64));} Public String toString () {return "p[" + ID + "]"; }}
Consumer:
/** * Consumerthread: Consumer thread * */package threadprogramming.basic.simulation;import java.util.concurrent.TimeUnit; public class Consumerthread implements Runnable {private static volatile Boolean Endflag = false;private final int Id;priv Ate sharedcharbuffer buffer;public consumerthread (int id, sharedcharbuffer buffer) {this.id = Id;this.buffer = buffer;} public static void Cancel () {Endflag = true;} public Boolean isCanceled () {return endflag = = true;} /** * Consume: * When there are characters in buffer buffers, the characters are removed to show "equivalent to consumer". * */public char consume () {return Buffer.fetch ();} /** * Consumer tasks: As long as the task is not canceled and the buffer is not empty, the character consumption is taken out of the buffer. */public void Run () {while (!iscanceled () &&! Thread.interrupted ()) {synchronized (buffer) {while (Buffer.isempty ()) {try {buffer.wait ();} catch ( Interruptedexception e) {System.out.println (this + "interrupted.");}} System.out.println (Timeindicator.getcurrtime () + ": \ T" + this + "remove character:" + consume ()); System.out.println (Timeindicator.getcurrtime () + ": \ T" + this + ": \t\t\t" + buffer);. Notifyall ();} try {TimeUnit.MILLISECONDS.sleep;} catch (Interruptedexception e) {System.out.println (this + "interrupted.");}} System.out.println ("Exit from:" + This);} Public String toString () {return "c[" + ID + "]";}}
Finite character buffers: Sharedcharbuffer.java
/** * Sharedcharbuffer: Finite length character buffer * */package Threadprogramming.basic.simulation;public class Sharedcharbuffer {private Char[] Charbuffer; The limited-length character buffers used to produce and consume private int front; The position where the character will be taken is subscript private int rear; Subscript public Sharedcharbuffer (int capacity) {if (Charbuffer = = null) {Charbuffer = new char[capacity], where the character will be written;} Front = rear = 0;} /** * Determine if the buffer is full, full producer waits */public synchronized Boolean isfull () {return (rear+1)% charbuffer.length = front;} /** * Determine if the buffer is empty, the consumer waits for */public synchronized Boolean isEmpty () {return front = = rear;} /** * Write: Writes the given character to the buffer "changed buffer contents" * Synchronized keyword for implementing mutually exclusive access buffers * @param ch character that'll be written into the Buffe R. * */public synchronized void write (char ch) {Charbuffer[rear] = ch; Rear = (rear+1)% Charbuffer.length; }/** * Read: Reads the character of the given position in the buffer "does not change the buffer contents" * Synchronized keyword is used to implement the mutex access buffer * */public synchronized char read (int index) {return Charbuffer[index]; }/** * Fetch: Remove the character of the buffer given position "changed buffer contents"* Synchronized keyword is used to implement mutually exclusive access buffers * */public synchronized char fetch () {char ch = Charbuffer[front];front = (front + 1)% CH Arbuffer.length;return ch;} /** * Getstringofbuffer: string representation of buffer contents * @return string representation of the buffer ' s contents * */Public Synchronize D String toString () {if (IsEmpty ()) {return ' buffer is empty! ";} StringBuilder bufferstr = new StringBuilder ("Buffer contents:"); int i = Front;while ((i+1)% charbuffer.length! = rear) {BUFFERSTR.A Ppend (Charbuffer[i]); i = (i+1)% Charbuffer.length;} Bufferstr.append (Charbuffer[i]); return bufferstr.tostring ();}}
Producer-Consumer issues "Java implementation"