This is a count lock, plainly, is when you lock, only when the count is reduced to 0, will release the lock
Package cn.xf.cp.ch05; Public class Implements runnable{ @Override publicvoid run () { System.out.println ( "Do something ..."); } Public Static void Main (String []args) { new Thread (new taskrunable ()); T.start (); }}
Packagecn.xf.cp.ch05;ImportJava.util.concurrent.CountDownLatch;/*** * Function: 10 Threads Sync * Time: 6:08:46 * File: Readdata.java *@authorAdministrator **/ Public classreaddata{//private static int seek_num = 0; //run synchronously, and count time Public Static LongTimetasks (intNthreads,FinalRunnable Task)throwsinterruptedexception {//The start gate, which is used to delimit the start time of the thread synchronization FinalCountdownlatch startgate =NewCountdownlatch (1); //used to wait for all threads to end FinalCountdownlatch endgate =NewCountdownlatch (nthreads); for(inti = 0; i < nthreads; ++i) {//set write-out file start position, one long+ space is 10 bytes//Creating ThreadsThread T =NewThread () { Public voidrun () {Try { //wait for all threads to startstartgate.await (); Try{task.run ();//Start Thread } finally { //notification after the thread has finished runningEndgate.countdown (); } } Catch(Interruptedexception e) {} } }; T.start (); } LongStart =System.nanotime (); //unlock the start door, task begins to workStartgate.countdown (); //Lock the end, only reduce to 0 to unlockendgate.await (); LongEnd =System.nanotime (); returnEnd-start;//Time Results } Public Static voidMain (string[] args) {taskrunable tr=Newtaskrunable (); Try{System.out.println (Readdata.timetasks (10, tr)); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
Results
"Java Concurrency Programming Combat" 4, Countdownlatch