1 Package Threadl;2 3 import java.util.LinkedList;4 5 classQueue extends Linkedlist<string>{6 intlenght;7 PublicQueue () {8 9 }Ten One PublicQueue (intlength) { A This. Lenght =length; - } - the Public intGetLength () { - return This. Lenght; - } - + PublicString Shift () { - if(! This. IsEmpty ()) { + return This. Remove (); A}Else{ at return "it's empty."; - } - } - - Public voidpush (String ch) { - if( This. Size () <= This. Lenght) { in This. AddLast (CH); - } to } + - PublicBoolean isfull () { the if( This. Size () = = This. Lenght) { * return true; $}Else{Panax Notoginseng return false; - } the } + } A classdepot{ theQueue queue =NULL; + PublicDepot (intlength) { - This. Queue =NewQueue (length); $ } $ Static inti =1; - PublicSynchronizedvoidProduce (String ch) { - This. Notify (); the while( This. Queue.isfull ()) { - Try {Wuyi This. Wait (); the}Catch(interruptedexception e) { - e.printstacktrace (); Wu } - } About This. Queue.push (CH); $System. out. println ("production section \ t"+ (i++) +"\ t products \ t"+ This. Queue.getlast ()); - } - PublicSynchronizedvoidconsume () { - This. Notify (); A while( This. Queue.isempty ()) { + Try { the This. Wait (); -}Catch(interruptedexception e) { $ e.printstacktrace (); the } the } theSystem. out. println ("consumes the first \ t"+ (-I.) +"\ t products \ t"+ This. Queue.getfirst ()); the This. Queue.shift (); - } in } the classProduce implements runnable{ the Depot Depot; About PublicProduce (Depot Depot) { the This. depot=Depot; the } the Public voidrun () { + for(intI=0;i<Ten; i++){ - This. Depot.produce ("A"); the }Bayi } the } the classconsume implements runnable{ - Depot Depot; - Publicconsume (Depot Depot) { the This. depot=Depot; the } the Public voidrun () { the for(intI=0;i<Ten; i++){ - This. Depot.consume (); the } the } the }94 Public classTHREAD10 { the Public Static voidMain (string[] args) { theDepot Depot =NewDepot (8); theThread Pro =NewThread (NewProduce (depot));98Thread con =NewThread (Newconsume (depot)); About Pro.start (); -Pro.setname ("PRO");101 Con.start ();102Con.setname ("CON");103 }104}
Do not look at the hands of the blind: producer consumers-synchronization problems