The number of users who can achieve traffic control while accessing files
import java.util.concurrent.executorservice;import java.util.concurrent.executors;import java.util.concurrent.semaphore;public class semaphoretest { public Static void main (String[] args) { Executorservice service = executors.newcachedthreadpool (); final semaphore sp = new semaphore (3);//Create Semaphore semaphore, initialize license size 3 runnable runnable = new runnable () { public void run () { try { sp.acquire ()///request permission to continue execution if a license is available, minus 1 of the license. Otherwise enter the blocking state } catch (INTERRUPTEDEXCEPTION&NBSP;E1) { e1.printstacktrace (); } &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "Enter, currently available" + (3-sp.availablepermits ()) + "concurrency"); try { thread.sleep ((Long) (Math.random () *10000)); } catch (interruptedexception e) { &nBsp; e.printstacktrace (); } &NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + " Going away "); sp.release ();//release permission, Number of licenses plus 1 //The following code is sometimes executed inaccurately because it does not synthesize atomic units with the above code &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Threads" + Thread.CurrentThread (). GetName () + "left, currently available" + (3-sp.availablepermits ()) + "concurrency"); } }; for (int i=0;i<10;i++) { service.execute (runnable); //Submit 10 Quests } } }
This article is from the "thick, thin hair, ax" blog, please be sure to keep this source http://tianxingzhe.blog.51cto.com/3390077/1716824
Semaphore maintaining the number of threads currently accessing itself