In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use java concurrency tools Semaphore and Exchanger. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.
1. Control concurrent access to resources-- Semaphore
Semaphore can be understood as a semaphore, which is used to control the number of threads that resources can be accessed concurrently, so as to ensure that multiple threads can use specific resources reasonably.
Semaphore is the equivalent of a license, and the thread needs to obtain the license through the acquire method before the thread can continue to execute, otherwise it will have to wait for blocking in that method. After performing the business function, the license needs to be returned through the release () method so that other threads can obtain the license to continue execution.
Semaphore can be used for traffic control, especially in application scenarios where public resources are limited, such as database connections. If multiple threads read the data and need to save the data in the database, and the maximum number of database connections available is only 10, then you need to use Semaphore to control the maximum number of threads that can access the database connection resources concurrently. Semaphore is particularly appropriate in application scenarios that limit the use of resources.
Here's a look at the main methods of Semaphore:
/ / obtain a license. If it cannot be obtained, void acquire () throws InterruptedException// is basically the same as the acquire method until it can be obtained, except that this method can obtain more than one license void acquire (int permits) throws InterruptedException// release license void release () / / release a specified number of licenses void release (int permits) / / attempt to obtain a license, and return true immediately if it is successful, otherwise The return falseboolean tryAcquire () / / is the same as the tryAcquire method, except that you can specify to obtain multiple licenses boolean tryAcquire (int permits) / / to attempt to obtain the license, and return true if it can be obtained immediately or within a specified time, otherwise return falseboolean tryAcquire (long timeout, TimeUnit unit) throws InterruptedException// is the same as the previous method It's just that here you can get multiple licenses boolean tryAcquire (int permits, long timeout, TimeUnit unit) / / return the number of licenses currently available int availablePermits () / / return the number of threads waiting for a license int getQueueLength () / / whether there are threads waiting for a license boolean hasQueuedThreads () / / get a collection of all threads waiting for a license Collection getQueuedThreads ()
In addition, the construction method of Semaphore also supports specifying that it is fair enough, and the default is unfair, which is also to ensure throughput.
An example
Let's use a simple example to illustrate the specific use of Semaphore. Let's simulate a scene like this. One day, the head teacher needed 10 students in the class to come to the podium to fill out a form, but the teacher only prepared five pens, so he could only guarantee that only five students could get the pen and fill in the form at the same time. The students who did not get the pen could only get the pen to fill out the form after the students in front of them had finished using it. The sample code is as follows:
Public class SemaphoreDemo {/ / means that the teacher has only 10 pens private static Semaphore semaphore = new Semaphore (5); public static void main (String [] args) {/ / means 50 students ExecutorService service = Executors.newFixedThreadPool (10); for (int I = 0; I)
< 10; i++) {service.execute(() ->{try {System.out.println (Thread.currentThread (). GetName () + "students are ready to get a pen."); semaphore.acquire (); System.out.println (Thread.currentThread (). GetName () + "students get a pen"); System.out.println (Thread.currentThread (). GetName () + "fill in the form ing."); TimeUnit.SECONDS.sleep (3); semaphore.release () System.out.println (Thread.currentThread (). GetName () + "fill out the form and return the pen!") ;} catch (InterruptedException e) {e.printStackTrace ();}});} service.shutdown ();}}
Output result:
Pool-1-thread-1 students prepare to get pens. Pool-1-thread-1 students get pens pool-1-thread-1 fill-in forms ing.pool-1-thread-2 students prepare to get pens. Pool-1-thread-2 students get pens pool-1-thread-2 fill-in forms ing.pool-1-thread-3 students prepare to get pens. Pool-1-thread-4 students prepare to get pens. Pool-1-thread-3 students get pens pool-1-thread-4 students get pens pool-1-thread-4 fill out forms ing.pool-1-thread-3 fill out forms ing.pool-1-thread-5 prepare to get pens. Pool-1-thread-5 students get pens pool-1-thread-5 Fill out the form ing.pool-1-thread-6 students prepare to get pens. Pool-1-thread-7 students prepare to get pens. Pool-1-thread-8 students prepare to get pens. Pool-1-thread-9 students prepare to get pens. Pool-1-thread-10 students prepare to get pens. Pool-1-thread-4 fill out the form Returned the pen! Pool-1-thread-9 got the pen pool-1-thread-9 filled in the form ing.pool-1-thread-5 filled out the form and returned the pen! Pool-1-thread-7 got the pen pool-1-thread-7 fill-in form ing.pool-1-thread-8 got the pen pool-1-thread-8 filled out the form ing.pool-1-thread-1 filled out the form and returned the pen! Pool-1-thread-6 got the pen pool-1-thread-6 filled in the form ing.pool-1-thread-3 filled out the form and returned the pen! Pool-1-thread-2 filled out the form and returned the pen! Pool-1-thread-10 got the pen pool-1-thread-10 filled in the form ing.pool-1-thread-7 filled out the form and returned the pen! Pool-1-thread-9 filled out the form and returned the pen! Pool-1-thread-8 filled out the form and returned the pen! Pool-1-thread-6 filled out the form and returned the pen! Pool-1-thread-10 filled out the form and returned the pen!
According to the analysis of the output results, the maximum number of licenses allowed by Semaphore is 5, that is, the maximum number of threads allowed for concurrent execution is 5. It can be seen that the first five threads (the first five students) first get the pen and then fill in the form, while the five threads of 6-10 can only block waiting because they cannot get permission.
When the thread pool-1-thread-4 releases the license, pool-1-thread-9 can get the license and continue to execute. The same is true for the execution of other threads.
As can be seen from this example, it is quite appropriate for Semaphore to be used for concurrent access control of special resources. If there is a business scenario that requires traffic control, Semaphore can be given priority.
two。 A tool for exchanging data between threads-- Exchanger
Exchanger is a tool class for collaboration between threads that can be exchanged between two threads. It provides an exchange synchronization point where two threads can exchange data.
The specific exchange of data is achieved through the exchange method. If one thread executes the exchange method first, it will synchronously wait for another thread to also execute the exchange method. At this time, both threads reach the synchronization point, and the two threads can exchange data.
In addition to a no-parameter construction method, the main method of Exchanger is also very simple:
/ / when one thread executes the method, it waits for another thread to execute the method, so both threads reach the synchronization point / / exchange data to another thread, and the returned data V exchange (V x) throws InterruptedException// is basically the same as the previous method, except that when this method waits synchronously, it increases the timeout V exchange (V x, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException.
An example
Exchanger is easy to understand, so here's a simple example to see how to use it. Let's simulate such a scene, in the youthful high school days, during the end of class, boys often send love letters to girls they like in the hallway. I believe everyone has done such a thing:). The boy will first go to the door of the girl's classroom, and then wait for the girl to come out, where there is a synchronization point, and then exchange gifts with each other, that is, exchange data with each other. Now, let's simulate this scenario.
Public class ExchangerDemo {private static Exchanger exchanger = new Exchanger (); public static void main (String [] args) {/ / represents boys and girls ExecutorService service = Executors.newFixedThreadPool (2); service.execute (()-> {try {/ / what boys say to girls String girl = exchanger.exchange ("I've actually had a crush on you for a long time"); System.out.println ("girls say:" + girl);} catch (InterruptedException e) {e.printStackTrace ();}}) Service.execute (()-> {try {System.out.println); TimeUnit.SECONDS.sleep (3); / what boys say to girls String boy = exchanger.exchange ("I like you, too"); System.out.println ("boys say:" + boy);} catch (InterruptedException e) {e.printStackTrace ();}});}}
Output result:
The girl walks out of the classroom slowly. The boy said: I have actually had a crush on you for a long time. The girl said, "I like you, too."
This example is simple and illustrates the basic use of Exchanger. When both threads reach the synchronization point where the exchange method is called, the two threads can exchange data with each other.
On how to use java concurrency tools Semaphore and Exchanger to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can 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: 230
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.