Java implements thread synchronization. You can use synchronized, wait (), notitfy (), and notifyall (). Assume that a thread (producer) produces a product and a thread (consumer) consumes the product, the Resource Access time is random, so that the producer can only produce after the product (Resource) consumption is complete, and the consumer can consume the product only when the product is available, this means that the resource must be synchronized, and the code used for the resource must be locked.
The following are my implementation methods:
Package COM. lzb. common; import Java. util. random; import Java. util. concurrent. timeunit;/***** Function Description: producer consumer * Note: The lock synhronized is placed in the "internal method of the Resource class ", instead of in the thread Code */public class productercustomer {private pcresource Pc = new pcresource (); // the producer and consumer call time is random private random Rand = new random (50 ); public void Init () {// producer new thread (New runnable () {public void run () {While (true) {PC. producter (); try {timeun It. milliseconds. sleep (Rand. nextint (1000);} catch (interruptedexception e) {e. printstacktrace ();}}}}). start (); // consumer new thread (New runnable () {public void run () {While (true) {PC. customer (); try {timeunit. milliseconds. sleep (Rand. nextint (1000);} catch (interruptedexception e) {e. printstacktrace ();}}}}). start ();} public static void main (string [] ARGs) {productercustomer startpc = ne W productercustomer (); startpc. init () ;}/ ***** Function Description: Synchronize resources **/class pcresource {Private Static final integer max = 1; Private Static final integer min = 0; private int Product = 0; // synchronous mutex communication mark private Boolean isrunning = true;/*** Function Description: production product, which is suspended after a product is produced, wait until the consumer consumption is completed */Public synchronized void producter () {While (isrunning) {try {Wait () ;}catch (interruptedexception e) {e. printstacktrace () ;} Product ++; system. out. println ("--------> product" + product + "good"); If (product> = max) break;} isrunning = false; running y ();} /***** Function Description: consumer. when the product is 0, wait for the producer to produce the product */Public synchronized void customer () {While (! Isrunning) {try {Wait ();} catch (interruptedexception e) {e. printstacktrace ();} product --; system. out. println ("Limit" + product + "goods <----------"); If (product <= min) {break ;}} isrunning = true; running y ();}}