Semaphore
The underlying implementation principle of the class involves more complex thread synchronization and operating system-related mechanisms, and is implemented based on the underlying counters and thread waiting queues.
In Java, Semaphore
classes use an inner Sync
class to implement synchronization and thread waiting mechanisms. Specifically, Semaphore
the class uses AQS (AbstractQueuedSynchronizer)
a subclass of to manage the thread's permission state and wait queue.
AQS
It is a key class in the Java concurrency package, which is used to implement the basic framework of locks and synchronizers. It represents the number of permits through an integer counter, and manages the threads waiting to obtain permits through an internal waiting queue. AQS
Provides basic implementations of atomic operations and thread wait queues.
For Semaphore
the class , Sync
the class inherits from AQS
and overrides some of its methods to implement license acquisition and release operations. Specifically, Sync
the class overrides tryAcquireShared
the and tryReleaseShared
methods to implement the permission acquisition and release logic. tryAcquireShared
The method is used to try to obtain a license. If the number of licenses is greater than zero, the acquisition is successful; otherwise, a negative value is returned to indicate that the acquisition failed and enter the waiting queue. tryReleaseShared
The method is used to release the license, increase the number of licenses by one, and wake up the threads in the waiting queue.
Through AQS
the internal mechanism of , Semaphore
the class can realize the acquisition and release of the license, and correctly manage the threads in the waiting queue to ensure the synchronization and mutual exclusion of the threads.
It should be noted that Semaphore
the underlying implementation principles of classes may vary with different Java versions and specific implementations. The above description is a common implementation. The actual implementation details may vary between different implementations of the JVM.