Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Semaphore to implement semaphores in Java multithread

2025-03-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "Java multithread how to use Semaphore to achieve semaphores", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Java multithreading how to use Semaphore to achieve semaphores" bar!

Foreword:

Semaphore is a count semaphore. Semaphore manages a range of licenses. Each acquire method blocks until a license can be obtained and then taken away; each release method adds a license, which may release a blocked acquire method. However, there is no actual license object, and Semaphore just maintains a number of licenses available.

Semaphore maintains the current number of threads accessing itself and provides a synchronization mechanism. Using Semaphore, you can control the number of threads that access resources at the same time, for example, the number of concurrent access allowed for a file.

1 the main methods of Semaphore

Semaphore (int permits): constructor that creates a count semaphore with a given number of permissions and sets it to an unfair semaphore.

Semaphore (int permits,boolean fair): constructor that creates a count semaphore with a given number of permissions and sets it to a fair semaphore when fair equals true.

Void acquire (): the current thread attempts to block to get 1 license.

This process is blocked and waits for a license until any of the following occurs:

If the current thread has obtained 1 available license, it will stop waiting and continue execution.

If the current thread is interrupted, it throws an InterruptedException exception, stops waiting and continues execution.

Void acquire (int n): gets a given number of permissions from this semaphore and blocks the thread until these permissions are provided.

The current thread attempts to block to obtain multiple licenses.

This process is blocked and waits for a license until any of the following occurs:

If the current thread has obtained n available licenses, it will stop waiting and continue execution.

If the current thread is interrupted, it throws an InterruptedException exception, stops waiting and continues execution.

Void release (): releases a license and returns it to the semaphore.

Void release (int n): releases n licenses.

Int availablePermits (): the number of licenses currently available.

Void acquierUninterruptibly (): the current thread attempts to block to get a license (uninterruptible).

This process is blocked and waits for a license until any of the following occurs:

If the current thread has obtained 1 available license, it will stop waiting and continue execution.

Void acquireUninterruptibly (permits): the current thread attempts to block to obtain multiple licenses.

This process is blocked and waits for a license until any of the following occurs:

If the current thread has obtained n available licenses, it will stop waiting and continue execution.

The current thread of boolean tryAcquire () is trying to get a license.

This process is non-blocking, and it is only an attempt when the method is called.

If the current thread obtains an available license, it stops waiting, continues execution, and returns true.

If the current thread does not have this license, it will also stop waiting, continue execution, and return false.

Boolean tryAcquire (permits): the current thread is trying to obtain multiple licenses.

This process is non-blocking, and it is only an attempt when the method is called.

If the current thread obtains permits's available licenses, it stops waiting, continues execution, and returns true.

If the current thread does not have a permits license, it also stops waiting, continues execution, and returns false.

Boolean tryAcquire (timeout,TimeUnit): the current thread is blocking an attempt to obtain a license within a limited time.

This process is blocked and waits for a license until any of the following occurs:

When the current thread has obtained an available license, it stops waiting, continues execution, and returns true.

If the current thread wait time timeout timed out, it will stop waiting, continue execution, and return false.

If the current thread is interrupted within timeout time, it throws an InterruptedException once, stops waiting and continues execution.

Boolean tryAcquire (permits,timeout,TimeUnit): the current thread is blocking an attempt to obtain a permits license within a limited time.

This process is blocked and waits for a license until any of the following occurs:

When the current thread has obtained the available permits licenses, it stops waiting, continues execution, and returns true.

If the current thread wait time timeout timed out, it will stop waiting, continue execution, and return false.

If the current thread is interrupted within timeout time, it throws an InterruptedException once, stops waiting and continues execution.

2 examples explain public class SemaphoreTest {private static final Semaphore semaphore = new Semaphore (3); public static void main (String [] args) {Executor executor = Executors.newCachedThreadPool (); String [] name = {"Jack", "Pony", "Larry", "Martin", "James", "ZhangSan", "Tree"}; int [] age = {21, 22, 23, 24, 26, 27}; for (int item0) I current) / / underflow throw new Error ("Permit count underflow"); / / if CAS changes successfully if (compareAndSetState (current, next)) return;}}

As you can see above, it is CAS that changes the state variable in AQS because it represents the number of licenses.

Get the remaining number of licenses

Semaphore can also take all the remaining licenses at once, which is the drain method.

As follows:

Public int drainPermits () {return sync.drainPermits ();}

The implementation of Sync is as follows:

Final int drainPermits () {for (;;) {int current = getState (); if (current = = 0 | | compareAndSetState (current, 0)) return current;}}

As you can see, it is CAS that sets the number of licenses to 0.

Thank you for reading, the above is the content of "Java multithreading how to use Semaphore to achieve semaphores", after the study of this article, I believe you have a deeper understanding of how Java multithreads use Semaphore to achieve semaphores, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report