Import Java.util.arraylist;import Java.util.list;public class Produceandconsume {public static final Object signal = new O Bject ();p ublic static list<string> List = new arraylist<string> ();p ublic static void Main (String args[]) {THR EAD produce = new Thread (new Produce ()); Thread consume = new Thread (new Consume ());p Roduce.start (); Consume.start ();}} Class produce implements runnable{@Overridepublic void Run () {int sequence = 0;while (true) {synchronized ( produceandconsume.signal) {for (int i = 0; i < 3; i++) {ProduceAndConsume.list.add (sequence + "commodity");} Sequence++;try {ProduceAndConsume.signal.notify (); ProduceAndConsume.signal.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}}}} Class consume implements runnable{@Overridepublic void Run () {int count = 0;while (Count < 5) {synchronized (Produceandco Nsume.signal) {try {ProduceAndConsume.signal.wait ();} catch (Interruptedexception e) {e.printstacktrace ();} if (ProduceAndConsume.list.size () > 0) {for (StringStr:ProduceAndConsume.list) {System.out.println (str);} ProduceAndConsume.list.clear (); count++; ProduceAndConsume.signal.notify ();}}}}
Note
1. Consumption and production be sure to use the same lock produceandconsume.signal
the role of 2.produceandconsume.signal.wait () is that the current thread is paused, releasing the lock Signal , go to the wait queue and wait for the signal of this semaphore (signal is also a lock) notification. Wait until the signal notification (and not the notification of other semaphores), the thread has the opportunity to go to the ready queue to compete for execution.
the role of 3.produceandconsume.signal.notify () is to notify a single thread waiting in signal of this semaphore to enter the ready queue from the waiting queue to prepare for the opportunity to compete for execution. But the thread that calls the ProduceAndConsume.signal.notify () method does not immediately release the lock, but instead releases the lock after the code is executed, because notify just notifies the other threads waiting on the semaphore to enter the ready queue, ready to compete for the lock.
Boards consumer Model