One 、Semaphore Function is introduced

Semaphore Class is equivalent to a thread counter , In obtaining Semaphore Object to set the total number of threads that can be generated ( Threads are not Semaphore Class generated , It just counts the number of threads ), establish Semaphore The class object is shown in the following method :

// Create a Semaphore object ,Sync sync The object is assigned the value NonfairSync object 
Semaphore sp = new Semaphore(1); // Create a Semaphore object ,Sync sync The object is assigned the value FairSync object
Semaphore sp = new Semaphore(1,true);

Call before creating thread Semaphore Class acquire() Method to determine whether a thread can also be created ,acquire() Method each time called, the total number of threads that can be created is reduced by one , And this method is a blocking method , If the current number of threads has reached the maximum, the thread will be blocked , When the conditions for creating a thread are met, the program continues , After the thread is running, it is called. Semaphore class release() Method to release the number of occupied creatable threads .

Conclusion :Semaphore Class can control the total number of threads created in concurrent situations

Two 、Semaphore Class method decomposition

The following is Semaphore Construction method of class :

 public Semaphore(int permits) {
sync = new NonfairSync(permits);
} public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);

The following is true NonfairSync Classes and FairSync Class source code , From the code, it seems that the two classes are right tryAcquireShared(int acquires) The implementation of the method is completely different , In fact, their implementation is basically the same ,NonfairSync Of the parent class of a class call nonfairTryAcquireShared(acquires) Method , The implementation of this method is as follows , By contrast, the difference is that FairSync Class called at method entry hasQueuedPredecessors() Method added if Judge ,hasQueuedPredecessors The code is as follows .

* NonFair version
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -2694183684443567898L; NonfairSync(int permits) {
} protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
} /**
* Fair version
static final class FairSync extends Sync {
private static final long serialVersionUID = 2014338818796000944L; FairSync(int permits) {
} protected int tryAcquireShared(int acquires) {
for (;;) {
if (hasQueuedPredecessors())
return -1;
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1192457210091910933L; final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
// before tail and on being accurate if the current
// thread is first in queue.
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
return h != t &&
((s = == null || s.thread != Thread.currentThread());

1、acquire()/acquire(int) Methods to introduce

As shown below ,acquire() Method calls the acquireSharedInterruptibly(int arg) Method , This method calls the tryAcquireShared(int arg) If no thread reaches the maximum number, execute doAcquireSharedInterruptibly(arg), As shown below, there is a dead loop in this method , When the number of threads that can be created meets the parameter arg when , Out of the loop , The code that creates the thread continues .

Conclusion :acquire() It's a blocking approach , Gets a given number of permissions from this semaphore , Blocking threads until these permissions are provided , Or when the current thread interrupts InterruptedException abnormal , Interrupt blocking .


 public void acquire() throws InterruptedException {
 public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
} private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r); = null; // help GC
failed = false;
if (shouldParkAfterFailedAcquire(p, node) &&
throw new InterruptedException();
} finally {
if (failed)

2、acquireUninterruptibly()/acquireUninterruptibly() Methods to introduce

These two methods and acquire() The two methods are basically the same , The only difference is , These two call methods acquireShared(int) There is no way to interrupt the current thread if Judge and the current method does not throw InterruptedException abnormal , So when the current thread is interrupted, the currently blocked method will not be interrupted .

Conclusion :acquireUninterruptibly It's a blocking approach , Gets a given number of permissions from this semaphore , Blocking threads until these permissions are provided .

public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)

3、 ... and 、 Sample demonstration

The following code is a simple example , Run the following code , From the order of the printed information, it can be verified that the method of obtaining semaphore is a blocking , Function verification of other methods , Let's finish it by ourselves !

public class ThreadTest {
public static void main(String[] args) throws Exception {
} public static void semaphoreTest() throws InterruptedException {
final Semaphore semaphore = new Semaphore(1);
Thread t1 = new Thread() {
public void run() {
try {
} catch (InterruptedException e) {
System.out.println(" Release ");

Multithreading —— Tool class Semaphore More articles about

  1. Java Concurrent ( 15、 ... and ): Concurrent tool class —— Semaphore Semaphore

    Do summary : 1.Semaphore What is it? ? Semaphore( Semaphore ) Is used to control the number of threads accessing a specific resource at the same time , It works by coordinating threads , To ensure the rational use of public resources . Compare it to a traffic light that controls the flow of traffic , such as XX The road should be clear ...

  2. Java Multithreading concurrent tool class - Semaphore Semaphore Object explanation

    Java Multithreading concurrent tool class -Semaphore Object explanation Through the previous study , We already know that Java In the multithreading concurrency scenario, there are two more tool classes : Do addition CycliBarrier Object and subtractive CountDownL ...

  3. Multithreaded tool class :CountDownLatch、CyclicBarrier、Semaphore、LockSupport

    ◆CountDownLatch◆ If there's a mission that wants to go down , But we have to wait until the other tasks are completed . Like you want to buy a house , But now you don't have any money . You'll have to wait for your paycheck this month . And then the year-end bonus went out . Then friends lend you money ...

  4. JUC—— Thread synchronization helper class (Semaphore,CountDownLatch,CyclicBarrier)

    The core of the lock mechanism is : Blocking , unblocked , But if it's just this function , that JUC It's not a good thread development framework , However, it is because of the juc It provides a large number of convenient synchronization tools and auxiliary classes . Semaphore The signal ...

  5. java Important multithreading tool classes in

    Preface When I learned multithreading before, I didn't learn the synchronization tool class of threads ( Auxiliary class ).ps: I didn't think I could use it for the time being , I don't care if I think it's a very deep knowledge point .. In a few days ago , My friend sent a better article Semaphore Here comes the article , And then, while browsing the blog ...

  6. 【Java Concurrent tool class 】Semaphore

    Preface 1965 year , Dutch computer scientist Dijkstra The proposed semaphore mechanism becomes an efficient process synchronization mechanism . After that 15 year , Semaphores have always been the terminator of concurrent programming .1980 year , The tube is put forward , Become the leader in concurrent programming after semaphores ...

  7. Java Loop fence counter of multithreading tool class

    Java Multi thread down loop counter Main contents of this paper :CyclicBarrier( In the following, Kaige uses cycBar Instead of ) Definition Introduction : Illustrate with examples : Code demonstration : From the source point of view principle and summary :CyclicBarrier And CountDow ...

  8. Java Design of multithread synchronization tool class Semaphore

    Semaphore Semaphores are usually used as a tool to control the number of concurrent threads , It can be used to limit the number of concurrent threads accessing resources at the same time . One .Semaphore Use Let's take a simple example to see Semaphore Specific use of , We ...

  9. j.u.c series (10)--- The concurrency tool class :Semaphore

    Write it at the front Semaphore It's a count semaphore , Its essence is a " Shared lock ". Semaphores maintain a semaphore permission set . Threads can be called acquire() To get permission for semaphores : When permission is available in the semaphore ...

Random recommendation

  1. Raspberry pie 2 Installation and use of millet WIfi(360 Xiaodu tencent wifi)

    to update 2015 year 11 month 16 Japan ,jessie Kernel version number 4.1.13(uname -a You can see ) It can be driven directly MT7601U, No manual compilation is required . end 2015-4-6, This article is based on raspberry pie 2,raspbian, Kernel version ...

  2. Android - Dynamic adjustment ListView Height

    Layout , If you design ListView The height of the package is the content of the package , that ListView The height of is changed with the number of its subentries , This can lead to ListView The position of some of the following controls will change with the time ListView A change in the height of ...

  3. Which Python memory profiler is recommended

  4. be based on XMPP Agreed aSmack Source code analysis

    We are studying how to realize Pushing During the function , Collected a lot about Pushing Information , One of them androidnp Open source projects use more people , But because there was no one to maintain it for a long time , hear bug There's a lot of chance , In order to stabilize our products in the future ...

  5. OC The wild pointer in ( Zombie pointer )

    It's class type variables that are involved in memory management , And in the OC We manipulate these objects by manipulating the pointer to them , Pointer is often ignored . Like defining UIView * view = [[UIView alloc]i ...

  6. Error compiling kernel :/bin/sh: 1: lzop: not found In the link above , It was found missing lzop work ...

  7. Simple string processing hdu1062 Text Reverse

    Although this topic is repeated AC, But in the heart still can't help but scold a sentence shit! It took an hour , The problem has been solved to a certain extent , But I'm not clear about reversing it , And still in the case of auxiliary array , It's so hard to straighten out relationships . Actually, I am ...

  8. spring annotation And AOP be based on @Aspect Of AOP To configure

    Spring AOP Section oriented programming , Can be used to configure transactions . Do the log . Authority verification . Do some processing when the user requests and so on . use @Aspect Make a cut , It can be realized directly . 1. First, define a facet class , add @Component  @A ...

  9. Nginx User rights authentication management

    First you need to compile into --with-http_request_model Configuration instructions :auth_request url | off; #url The address of the upstream server context: http/location To prepare ...

  10. The first 39 Chapter :MongoDB- colony --Replica Sets( Replica set )--- Basic principles of replica set

    ① The operation log oplog Oplog It's the master node local A fixed set in a database , Every write operation of the master node is recorded in sequence ,MongoDB The copy function of is to use oplog To achieve , By querying this collection, the backup node can know that it needs to enter ...