PackageCom.java.juc; Public classTestproductandconsumer { Public Static voidMain (string[] args) {Clerk Clerk=Newclerk (); Produce Produce=NewProduce (clerk); Consumer Consumer=NewConsumer (Clerk); NewThread (produce, "thread A"). Start (); NewThread (consumer, "Thread B"). Start (); NewThread (produce, "Thread AA"). Start (); NewThread (consumer, "Thread BB"). Start (); }}//Shop assistantclassClerk {Private intProduct = 0; Public synchronized voidget () { while(Product >= 1) {//This is used while not using if to prevent false wakeupSYSTEM.OUT.PRINTLN ("The product is full! "); Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println (Thread.CurrentThread (). GetName ()+ " : " + ++product); This. Notifyall (); } Public synchronized voidSale () { while(Product <= 0) {System.out.println (Stock "); Try { This. Wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println (Thread.CurrentThread (). GetName ()+ " : " + --product); This. Notifyall (); }}//producersclassProduceImplementsRunnable {PrivateClerk Clerk; PublicProduce (Clerk clerk) { This. Clerk =clerk; } @Override Public voidrun () { for(inti = 0; I < 20; i++) { Try{Thread.Sleep (200); } Catch(interruptedexception e) {e.printstacktrace (); } clerk.get (); } }}//ConsumerclassConsumerImplementsRunnable {PrivateClerk Clerk; PublicConsumer (Clerk clerk) { This. Clerk =clerk; } @Override Public voidrun () { for(inti = 0; I < 20; i++) {Clerk.sale (); } }}
Public final void Wait () throws Interruptedexception
Causes the current thread to wait until another thread invokes thenotify()
Method or thenotifyAll()
Method for this object. In other words, this method behaves exactly as if it simply performs the callwait(0)
.The current thread must own this object ' s monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object ' s Mon Itor to wake up either through a call to the notify
method or the notifyAll
method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
As in the one argument version, interrupts and spurious wakeups is possible, and this method should always being used in A loop:
Synchronized (obj) { while (<condition does not hold>) //In order to prevent spurious wakes should always be used in the Loop obj.wait (); ...//Perform action appropriate to condition
This method, should only being called by a thread, is the owner of this object ' s monitor. See thenotify
Method for a description of the ways in which a thread can become the owner of a monitor.
Java multithreaded producer consumer case-false wakeup