PackageCom.jayfulmath.designpattern.command;ImportJava.util.concurrent.Semaphore;/*P (S): ① The value of the semaphore S is reduced by 1, that is, S=s-1;② if s>=0, the process continues execution; otherwise the process is set to wait state. V (S): ① adds 1 to the value of the semaphore S, that is, s=s+1;② the process continues; if there is a waiting process in the waiting queue for that signal, a wait process is awakened. * * */ Public classPvobject {PrivateSemaphore Msemaphore =NULL; Private intMax_size = 0xFF; PrivateString name =NULL; PublicPvobject (intsize,string name) { if(size>0) {max_size=size; Msemaphore=NewSemaphore (size); } This. Name =name; } Publicpvobject (String name) {max_size= 1; Msemaphore=NewSemaphore (1); This. Name =name; } Public voidInit (intstatus) { if(status<0 | | status>max_size) {System.out.println ("[Pvobject][init]" +name+ "Wrong,status:" +status); return; } if(Status = =max_size) { return; } Try{msemaphore.release (max_size); Msemaphore.acquire (max_size-status); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public voidP () {Try { //Msemaphore.acquire (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } Public voidV () {msemaphore.release (); }}
Max_size The number of semaphores allowed to be used simultaneously, the default is 1.
Java implementation of PV operations