Java implementation of PV operations

Source: Internet
Author: User

 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.