Java producer and consumer models are a classic example of Java's lock mechanism, thread security and concurrent programming, I will share with you several different implementations I have encountered.
1. Use the synchronized keyword
Synchronized is used to apply synchronization locks to ensure thread security. Synchronized locks have been greatly optimized since 1.6. In general, synchronized locks are sufficient for synchronization.
Public class producerandconsumer {public static void main (string [] ARGs) {syncstack Ss = new syncstack (); // producer thread T1 = new thread (new producer (SS )); // consumer thread t2 = new thread (new consumer (SS); t1.start (); t2.start () ;}} class entity {int ID; entity (int id) {This. id = ID;} Public String tostring () {return "entity:" + ID;} class syncstack {int Index = 0; entity [] arrwt = new entity [6]; public synchronized void push (entity wt) {If (Index = arrwt. length) Try {This. wait ();} catch (interruptedexception e) {e. printstacktrace ();} This. Y (); arrwt [Index] = wt; index ++;} public synchronized void POP (entity wt) {If (Index = 0) {try {This. wait ();} catch (interruptedexception e) {e. printstacktrace () ;}} this. notify (); index -- ;}} class producer implements runnable {syncstack Ss = NULL; Producer (syncstack SS) {This. ss = SS;} public void run () {for (INT I = 0; I <20; I ++) {entity E = new entity (I); try {thread. sleep (1000);} catch (interruptedexception E1) {e1.printstacktrace ();} ss. push (E); system. out. println ("produced" + E) ;}} class Consumer implements runnable {syncstack Ss = NULL; public consumer (syncstack SS) {This. ss = SS;} public void run () {for (INT I = 0; I <20; I ++) {entity Wt = new entity (I ); try {// random sleep for a period of time thread. sleep (INT) (math. random () * 3000);} catch (interruptedexception e) {e. printstacktrace ();} ss. pop (wt); system. out. println ("consumed" + wt );}}}
Running result:
Produced entity: 1 consumed entity: 1 produced entity: 2 produced entity: 3 consumed entity: 2 produced entity: 4 produced entity: 5 consumed entity: 3
2. Use reentrantlock and condition
<! -- Generated by javadoc (build 1.6.0-beta2) on Fri Mar 09 12:53:21 CST 2007 -->
<NoScript> </NoScript>
Reentrantlock Is A reentrant lock, which is added from jdk1.5. A reentrant mutex lock hassynchronized
The method and the implicit monitor lock accessed by the statement have the same basic behavior and semantics, but are more powerful.
Condition condition (also knownCondition queueOrCondition variable), It
Replaces the use of the object monitor method. (For details, refer to the API)
Import Java. util. concurrent. locks. condition; import Java. util. concurrent. locks. lock; import Java. util. concurrent. locks. reentrantlock; public class producerandconsumer {final lock = new reentrantlock (); // reentrant lock final condition notfull = lock. newcondition (); // non-full condition final condition notempty = lock. newcondition (); // non-null condition final object [] items = new object [100]; int putptr, takeptr, count; Public void put (Object O) throws interruptedexception {lock. lock (); // lock the operation to ensure thread security. Try {While (COUNT = items. length) {notfull. wait () ;}items [putptr] = O; If (++ putptr = items. length) putptr = 0; ++ count; notempty. signal ();} finally {lock. unlock () ;}} public object take () throws interruptedexception {lock. lock (); // try {While (COUNT = 0) notempty. await (); object o = items [takeptr]; If (takeptr = items. length) takeptr = 0; -- count; notfull. signal (); return O;} finally {lock. unlock () ;}} public static void main (string [] ARGs) {final producerandconsumer PAC = new producerandconsumer (); // simulate consumer new thread (New runnable () {public void run () {try {for (;) {PAC. take (); system. out. println (thread. currentthread (). getname () ;}} catch (interruptedexception e) {e. printstacktrace ();}}}). start (); // simulate producer new thread (New runnable () {public void run () {try {for (INT I = 0; I <10; I ++) {object o = new object (); PAC. put (o); system. out. println (thread. currentthread (). getname () ;}} catch (interruptedexception e) {e. printstacktrace ();}}}). start ();}}
3. Use semaphore
<! -- Generated by javadoc (build 1.6.0-beta2) on Fri Mar 09 12:53:11 CST 2007 -->
<NoScript> </NoScript>
Semaphore: A count semaphore. In terms of concept, semaphores maintain a license set. If necessary, each acquire () is blocked before the license is available. Each relase adds a license, which may release a blocked recipient. However, do not use the actual license object,Semaphore
Only the available license numbers are counted and corresponding actions are taken. Semaphore is usually used to limit the number of threads that can access certain resources (physical or logical.
Import Java. util. concurrent. semaphore; public class testsemaphore {final static boundbuffer buffer = new boundbuffer (); public static void main (string [] ARGs) {// start three threads each for (INT I = 0; I <3; I ++) {New thread (new producer ()). start (); New thread (new consumer ()). start () ;}} static class boundbuffer {final semaphore notfull = new semaphore (10); Final semaphore notempty = new semaphore (0); // The input parameter is 1, to simulate a mutex lock final semaphore mutex = new semaphore (1); object [] items = new object [10]; int putptr, takeptr; static int count, put, take; public void put (Object O) {try {// get the put permission first, get the mutex lock while reducing the notfull license. acquire (); // Add mutex lock to ensure thread security mutex. acquire (); items [putptr] = O; If (++ putptr = items. length) {putptr = 0;} + + count; ++ put; system. out. println ("A total of" + Put + "," + Count + ");} catch (interruptedexception e) {e. printstacktrace ();} finally {// release mutex. release (); // note that notempty is used here. release (). This license is + 1, indicating that a new product // consumer thread can also be used to consume notempty. release () ;}} public object take () {try {notempty. acquire (); mutex. acquire (); object o = items [takeptr]; If (++ takeptr = items. length) takeptr = 0; -- count; ++ take; system. out. println ("total consumption" + take + "," + Count + "); return O;} catch (interruptedexception e) {e. printstacktrace (); return NULL;} finally {mutex. release (); // notfull. release () indicates that a put permission is added, and the producer can continue putnotfull. release () ;}} static class Consumer implements runnable {public void run () {While (true) {buffer. take (); try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}}} static class producer implements runnable {public void run () {While (true) {object o = new object (); buffer. put (o); try {thread. sleep (500);} catch (interruptedexception e) {e. printstacktrace ();}}}}}
Running result:
A total of 1 production, 1 production, 2 production, 3 production, and 3 consumption, two of the remaining items are consumed in total, and one is consumed in total, three are generated in total, and one is produced in total, 2 more .......
You can also share some other implementation methods.