Import Java.util.linkedlist;import Java.util.list;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class PC {private static Final lock lock = new Reentrantlock ();p rivate static final Condition empty = Lock.newcondition ();p rivate static final Cond ition full = lock.newcondition ();p rivate static final list<integer> List = new linkedlist<> ();p rivate static I NT size = 0;private static int maxSize = 5;private static int product = 1;public static void put () {lock.lock (); try {while (size = = maxSize) {empty.await ();} List.add (product); size++; System.out.println ("put" + product);p roduct++;full.signal ();} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.unlock ();}} public static void Take () {lock.lock (); try {while (size = = 0) {full.await ();} int tep = list.remove (0); size--; System.out.println ("take" + Tep); empty.signal ();} catch (Interruptedexception e) {e.printstacktrace ();} finally {Lock.unlock ();}} Class Producer implements Runnable {@Overridepublic void Run () {for (int i = 1; i <; i++) {put (); try {thread.sleep (1 00);} catch (Interruptedexception e) {e.printstacktrace ();}}}} Class Consumer implements Runnable {@Overridepublic void Run () {for (int i = 1; i <, i++) {take (); try {thread.sleep ( 1000);} catch (Interruptedexception e) {e.printstacktrace ();}}}} public static void Main (string[] args) {pc PC = new PC (); new Thread (Pc.new Producer ()). Start (); New Thread (Pc.new Consumer ( ). Start (); New Thread (Pc.new Producer ()). Start (); New Thread (Pc.new Consumer ()). Start ();}}
Put 1take 1put 2take 2put 3put 4put 5put 6put 7take 3take 4put 8put 9take 5take 6put 10put 11take 7take 8put 12put 13take 9take 10put 14put 15take 11take 12put 16put 17take 13take 14put 18take 15take 16take 17take 18
Java Multithreaded shared variables