Or in the application of the previous article, the lock that Xiao Ming and Xiao Qiang hold, one by one, the optimized code is as follows:
PackageCom.smikevon.concurrent.tools;ImportJava.util.concurrent.CountDownLatch;/*** @description: Requirements: Mother cooking, but this time has not bought food, there is no soy sauce. In order to eat more quickly, mother, Xiao Ming, Xiao Qiang, respectively action, * Mother is responsible for ringing the cooking bell (no move before the bell rang), the two brothers can start, and then the mother clean up the kitchen to adjust the material, Xiao Ming is responsible for the purchase of vegetables, Qiang buy soy sauce, work together to complete this job * An improvement to the testcountdownlatch_01, 01, a thread set a countdownlatch, where the overall setting of a * * Feature: All other threads executed, the execution of the target thread (that is, the execution of the Awai T's thread) ** @date: September 17, 2014 PM 2:41:50*/ Public classtestcountdownlatch_02 { Public Static voidMain (string[] args) {//Number of rings Final intBellringcount = 1; //who needs to wait (thread) Final intPeoplecount = 2; FinalCountdownlatch Bellringlatch =NewCountdownlatch (Bellringcount); FinalCountdownlatch Buylatch =NewCountdownlatch (Peoplecount); NewThread (NewRunnable () { Public voidrun () {Try{System.out.println ("Ready to cook, oh!" "); System.out.println ("Ding ding ding!!!"); /*** This code and the following order reversal will cause deadlocks*/Bellringlatch.countdown (); //wait for the food and the soy sauce to buy backbuylatch.await (); System.out.println ("I am a mother, the vegetables and the soy sauce are all together, I began to cook!" "); } Catch(interruptedexception e) {e.printstacktrace (); } } },Mom). Start (); //Xiaoming waits for the bell to go and buy food. NewThread (NewRunnable () { Public voidrun () {Try{System.out.println ("I am xiaoming, I am going to buy food (to go)!" "); Bellringlatch.await (); System.out.println ("I am xiaoming, I have bought the dish (get back)!" "); } Catch(interruptedexception e) {e.printstacktrace (); } buylatch.countdown (); } },"Xiao Ming"). Start (); NewThread (NewRunnable () { Public voidrun () {Try{System.out.println ("I'm Xiao Qiang, I'm going to soy sauce." "); Bellringlatch.await (); System.out.println ("I am the cockroach, I have hit the soy sauce (get back)!" "); } Catch(interruptedexception e) {e.printstacktrace (); } buylatch.countdown (); } },Xiaoqiang). Start (); }}
Order of control threads using latching (Countdownlatch) (ii)