Notes [Java7 Concurrency Programming Manual]3.2 Concurrent access control of resources Semaphore semaphores

Source: Internet
Author: User

Notes [Java7 Concurrent Programming manual] series catalogue

Brief introduction

This paper studies the semaphore mechanism of signal volume.

Semaphore
    1. Nature is a shared lock
    2. The internal maintenance of an available signal set, to obtain the signal volume before the need to obtain the number of signals, after use, you need to release the signal volume, if not released, then the other waiting thread will be blocked until the acquisition semaphore or is interrupted
    3. My understanding is: The mutex is only one thread access at the same time, and here, is the same time allowed to obtain the semaphore of the thread concurrent access, but not to obtain the semaphore, it must wait for the signal to be released;
    4. Initializes the semaphore to 1 so that it can be used as a mutually exclusive lock with a maximum of one license available at the time of use. This is often referred to as a binary semaphore because it can only have two states: one available license, or 0 licenses available. When used in this manner, the binary semaphore has some attribute (different from many lock implementations), that is, the "lock" can be freed by the thread, rather than by the owner (because the semaphore has no ownership concept).
    5. The same semaphores are divided into "fair semaphores" and "non-fair semaphores", and their relationship is consistent with normal, but it also wraps up a layer of "semaphores".

Following the use of the Lezilai demo semaphore through the previous acquisition of Apple's price

Example 1: First take a look at the 3rd above
 Public  class Client {     Public Static void Main(string[] args) {FinalGoodinfo GI =NewGoodinfo (); thread[] Read =Newthread[Ten];//Read thread, read 10 times product Information         for(inti =0; I <Ten; i++) {Read[i] =NewThread (NewRunnable () {@Override                 Public void Run() {gi.getinfo ();        }            }); }Finalthread[] Write =Newthread[3];//write thread, modify price 3 times         for(inti =0; I <3; i++) {Final intFinali = i; Write[i] =NewThread (NewRunnable () {@Override                 Public void Run() {gi.setprice ();        }            }); } for(Thread t:write)        {T.start (); } for(Thread T:read)        {T.start (); }    }}/** Commodity Information class * *Class Goodinfo {PrivateString name ="Apple";//Product name    Private DoublePrice =Ten;//Commodity price    Private FinalSemaphore sh =NewSemaphore (3);//Application of 3 semaphores    /** * Read Product Information * * @return  * *     Public void GetInfo() {Try{Sh.acquire (1);//Get 1 semaphores, if not enough, the current thread waitsString name = This. Name;DoublePrice = This. Price; System.out.println (Thread.CurrentThread (). GetName () +"Thread Gets the product information:"+ name +":"+ price); }Catch(Exception e)        {E.printstacktrace (); }finally{sh.release ();//Release signal volume}    }/** * Revise the price of the product, increase by 1 */each time * */     Public void Setprice() {Try{Sh.acquire (1); This. Price = This. Price +1;//Purpose: Error data occurs when multiple threads are concurrent (data contention to verify that the thread that acquired the semaphore is a concurrent thread)System.out.println ("--------------"+ Thread.CurrentThread (). GetName () +"Thread modified the price of the product:"+ name +":"+ price); Thread.Sleep ( -); }Catch(Exception e)        {E.printstacktrace (); }finally{sh.release ();//If you comment this out, you can see that the other waiting to get the semaphore is not getting the semaphore. Since one of the three threads here takes up the available semaphore, the other threads can only wait for the available semaphore.}    }}

The result of a run:

--------------thread- OneThread modified product Price: Apple:11.0thread-5The thread gets the product information: Apple:10.0thread-7The thread gets the product information: Apple:11.0thread-0The thread gets the product information: Apple:11.0thread-1The thread gets the product information: Apple:11.0thread-2The thread gets the product information: Apple:11.0thread-4The thread gets the product information: Apple:11.0thread-3The thread gets the product information: Apple:11.0--------------thread-TenThread modified product Price: Apple:12.0thread-6The thread gets the product information: Apple:12.0--------------thread- AThread modified product Price: Apple:13.0thread-8The thread gets the product information: Apple:13.0thread-9The thread gets the product information: Apple:13.0

If the write price of the release signal is commented out, the result of the operation is

--------------thread- AThread modified product Price: Apple:11.0thread-8The thread gets the product information: Apple:10.0thread-0The thread gets the product information: Apple:11.0thread-4The thread gets the product information: Apple:11.0thread-2The thread gets the product information: Apple:11.0thread-3The thread gets the product information: Apple:11.0thread-1The thread gets the product information: Apple:11.0thread-6The thread gets the product information: Apple:11.0thread-5The thread gets the product information: Apple:11.0thread-7The thread gets the product information: Apple:11.0--------------thread-TenThread modified product Price: Apple:12.0--------------thread- OneThread modified product Price: Apple:13.0

The thread is not finished running, and the thread that does not get the semaphore is waiting. caused a deadlock.

Description
The results of the above operation can be seen as follows:
Thread 11 modifies the product result, but thread 5 and thread 11 concurrently get the original price of 10, causing thread 5 to get the wrong data information.

Example 2: Implementing Binary Semaphores

Set the parameters of the construction semaphore object for the example above to 1

new Semaphore(1);   /创建二进制信号量

One of the running results is

--------------thread-TenThread modified product Price: Apple:11.0--------------thread- OneThread modified product Price: Apple:12.0thread-1The thread gets the product information: Apple:12.0thread-2The thread gets the product information: Apple:12.0thread-5The thread gets the product information: Apple:12.0thread-6The thread gets the product information: Apple:12.0thread-9The thread gets the product information: Apple:12.0--------------thread- AThread modified product Price: Apple:13.0thread-0The thread gets the product information: Apple:13.0thread-4The thread gets the product information: Apple:13.0thread-3The thread gets the product information: Apple:13.0thread-7The thread gets the product information: Apple:13.0thread-8The thread gets the product information: Apple:13.0

Can be seen, and the mutex effect is consistent.

And this class of usage scenarios. I haven't figured it out for the moment. Why there is such a mechanism. As for the fair Semaphore and the non-fair semaphore, it is not demonstrated. It's very simple. You know what the difference between a mutex and a semaphore is.

Another method of Acquire
    1. acquireuninterruptibly
      In fact, it is almost acquire (), the underlying or called the Tryacquireshared (Arg) method, which gets a license from this semaphore and blocks it before a license is available.
    2. Tryacquire
      Try to get past the semaphore, return true, not return false, avoid thread blocking, and pay attention to this method when using a fair lock. would undermine fairness.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Notes [Java7 Concurrency Programming Manual]3.2 Concurrent access control of resources Semaphore semaphores

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.