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

What does Semaphore mean in Java concurrent programming

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

Share

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

This article will explain in detail what Semaphore means in Java concurrent programming. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Brief introduction

Semaphore is used to limit the number of concurrent threads accessing specific resources. Compared with the mutual exclusion of built-in lock synchronized and reentrant lock ReentrantLock, Semaphore can allow multiple threads to access shared resources at the same time.

The use of Semaphored

Construction method

Semaphore (int permits): create a Semaphore and specify the number of licenses. (fair strategy is unfair)

Semaphore (int permits, boolean fair): create a Semaphore and specify the number of licenses and fairness policy.

Core method

Acquire (): get a license from Semaphore and block waiting if it is not available until another thread releases a license or the current thread is interrupted.

Acquire (int permits): gets a specified number of licenses from Semaphore and blocks waiting if not until another thread releases the corresponding number of licenses or the current thread is interrupted.

AcquireUninterruptibly (): get a license from Semaphore and block waiting if it cannot be obtained until another thread releases a license. (do not respond to interrupts)

TryAcquire (): try to get a license from Semaphore. If you get it successfully, you will return true. If you fail to get it, you will return false without waiting. (unaffected by the fairness policy, licenses are obtained immediately when available)

TryAcquire (long timeout, TimeUnit unit): attempts to obtain a license from Semaphore. If it is successful, it returns true. If it fails, it waits for the specified time, and returns false until the waiting time ends and no license is obtained.

Release (): release a license.

Release (int permits): releases the specified number of licenses.

Example

There are a total of five licenses, and the first five threads that obtain the license begin to execute the task, and the unacquired thread enters a waiting state until the licensed thread releases the license, and then obtains the license to execute the task.

Public class Demo {public static void main (String [] args) {/ / create Semaphore Semaphore semaphore = new Semaphore (5) with 5 licenses; Runnable runnable = ()-> {String threadName = Thread.currentThread (). GetName (); try {/ / obtain a license semaphore.acquire () System.out.println (threadName + "execute tasks..."); Thread.sleep (3000);} catch (InterruptedException e) {e.printStackTrace ();} finally {/ / release a license semaphore.release ();}} ExecutorService executorService = Executors.newFixedThreadPool (10); for (int I = 0; I

< 10; i++){ executorService.execute(runnable); } executorService.shutdown(); }}/* 开始输出: * pool-1-thread-1执行任务... * pool-1-thread-5执行任务... * pool-1-thread-6执行任务... * pool-1-thread-7执行任务... * pool-1-thread-3执行任务... * 三秒后输出: * pool-1-thread-4执行任务... * pool-1-thread-8执行任务... * pool-1-thread-2执行任务... * pool-1-thread-10执行任务... * pool-1-thread-9执行任务... */使用Semaphore实现互斥 使用Semaphore实现互斥只需要将许可证数量设置为1,这样就可以保证只有一个线程能获取到许可证。 Semaphore semaphore = new Semaphore(1); 相比内置锁synchronized和重入锁ReentrantLock,使用Semaphore实现互斥有个明显的缺点:不可重入,没有释放许可证的情况下,再次调acquire方法将导致死锁。 示例: public class Demo { public static void main(String[] args) { Semaphore semaphore = new Semaphore(1); Runnable runnable = () ->

{String threadName = Thread.currentThread (). GetName (); try {/ / obtain a license semaphore.acquire (); System.out.println (threadName + "execute Task A..."); semaphore.acquire (); System.out.println (threadName + "execute Task B...") } catch (InterruptedException e) {e.printStackTrace ();} finally {/ / release a license semaphore.release ();}}; new Thread (runnable). Start ();}} / * * output result: * Thread-0 executes task A. , /

"execute Task B" will never print because there is only one license, and the second call to the acquire method will remain blocked because the license cannot be obtained.

This is the end of this article on "what is the meaning of Semaphore in Java concurrent programming". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

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