1 ImportJava.util.concurrent.ExecutorService;2 Importjava.util.concurrent.Executors;3 ImportJava.util.concurrent.Semaphore;4 5 /**6 * 14.JAVA5 's semaphere sync tool7 * Semaphore can maintain the number of threads currently accessing itself and provides a synchronization mechanism. 8 * Use semaphore to control the number of threads concurrently accessing resources, for example, to implement a9 * The number of concurrent accesses allowed by the file. Ten * The semaphore object of a single semaphore can implement the mutex function, and it can be One * One thread obtains a "lock" and another thread releases "lock", which can be applied to some occasions of deadlock recovery. A * @authorlitaiqing - * - */ the Public classSemaphoretest { - Public Static voidMain (string[] args) { -Executorservice Service =Executors.newcachedthreadpool (); - FinalSemaphore SP =NewSemaphore (3); + for(inti = 0; I < 10; i++) { -Runnable Runnable =NewRunnable () { + Public voidrun () { A Try { at Sp.acquire (); -}Catch(interruptedexception E1) { - e1.printstacktrace (); - } -SYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () -+ "Enter, current already" + (3-sp.availablepermits ()) + "concurrency"); in Try { -Thread.Sleep ((Long) (Math.random () * 10000)); to}Catch(interruptedexception e) { + e.printstacktrace (); - } theSYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () *+ "Leaving soon"); $ sp.release ();Panax Notoginseng //The following code is sometimes executed inaccurately because it does not synthesize atomic units with the above code -SYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () the+ "has left, currently has" + (3-sp.availablepermits ()) + "concurrency"); + } A }; the Service.execute (runnable); + } - } $}
14.java5 's Semaphere Sync Tool