Semaphore can maintain the number of threads currently accessing itself, and provides a synchronization mechanism. You can use semaphore to control the number of threads that access resources at the same time, for example, to implement the number of concurrent accesses allowed by a file.
Semaphore realize the function of similar toilets have 5 pits, if there are 10 people to the toilet, then how many people at the same time to go to the toilet. At the same time only 5 people can occupy, when one of the 5 people out of the way, of which the other 5 waiting for another one can be occupied.
The other 5 people waiting for them can be randomly given priority, or get an opportunity in arrival order, depending on the parameter options that are passed in when the semaphore object is constructed.
The semaphore object of a single semaphore can implement a mutex function, and it can be "locked" by one thread and released by another thread, which can be applied to some situations of deadlock recovery.
From here on the various synchronization tools examples of code, the effect of the field is not as good as copying the code into eclipse to explain the effect of intuitive and concise, so that the overall situation and the whole show in front of the students. Then you can take a line of people to write, so as to consolidate the principle and exercise everyone to write code ability and inspire thinking effect.
public class Semaphoretest {
publicstatic void Main (string[] args) {
Executorserviceservice = Executors.newcachedthreadpool ();
Final semaphore sp = new semaphore (3);
for (inti=0;i<10;i++) {
runnablerunnable = new Runnable () {
Publicvoid Run () {
try{
Sp.acquire ();
}catch (interruptedexception E1) {
E1.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () +
"Enter, currently existing" + (3-sp.availablepermits ()) + "concurrency");
try{
Thread.Sleep ((Long) (Math.random () *10000));
}catch (Interruptedexception e) {
E.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () +
"Going Away");
Sp.release ();
The following code sometimes executes inaccurately because it does not synthesize atomic cells with the above code
SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () +
"has been left, currently has" + (3-sp.availablepermits ()) + "concurrency");
}
};
Service.execute (runnable);
}
}
}