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 are the characteristics of the four common locks used by java threads

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "what are the characteristics of the four common locks of java threads". The content of the explanation is simple and clear, and it is easy to learn and understand. let's study and learn "what are the characteristics of the four common locks of java threads"?

one。 Synchronized

1. Introduction

The synchronized keyword is often used by Java to maintain data consistency. The shared resources are locked through synchronized, and the shared resources can be accessed only if they get the lock, so that the order of accessing the shared resources can be guaranteed.

two。 Mode of use

Add this keyword to the method, class, or code block that needs synchronization, so that at most one thread executes the synchronous code of the same object at the same time. It ensures that the decorated code will not be disturbed by other threads during execution.

Synchronized (obj) {

/ / method

…… .

}

3. Features and usage scenarios

Synchronized-decorated code has atomicity and visibility, and is used frequently in programs that need process synchronization, which can meet the general requirements of process synchronization.

4. Performance and precautions

The mechanism of synchronized implementation depends on JVM at the software level, so its performance will be improved with the continuous upgrade of the Java version; but it should be noted that when a thread waits for a lock through synchronized, it cannot be interrupted by Thread.interrupt (), so the program design must be checked to make sure it is reasonable, otherwise it may cause an embarrassing situation of thread deadlock.

two。 ReentrantLock

1. Introduction

ReentrantLock can reenter the lock, which, as its name implies, can be repeatedly entered by the thread for acquisition operations. ReentantLock inherits the interface Lock and implements the methods defined in the interface. In addition to completing all the work that synchronized can do, it also provides methods to avoid multithreaded deadlocks, such as responding to interrupt locks, polling lock requests, timing locks, and so on.

two。 Mode of use

ReentrantLock carries out locking and unlocking operations through the methods lock () and unlock (). Unlike the mechanism that synchronized will be automatically unlocked by JVM, ReentrantLock needs to be unlocked manually. In order to avoid the situation that the program cannot be unlocked normally due to an exception, the unlocking operation must be performed in the finally control block when using ReentrantLock. The usual usage is as follows:

Lock lock = new ReentrantLock (); try {lock.lock (); / / … Perform task operations 5} finally {lock.unlock ();}

3. Features and usage scenarios

ReentantLock inherits the interface Lock, while the mechanism of Lock implementation depends on the special CPU specification, which can be considered not restricted by JVM, and can be implemented through other language platforms; ReentrantLock is often used in high concurrency cases.

4. Performance

In multithreaded applications with small concurrency, the performance of ReentrantLock is almost the same as that of synchronized, but under the condition of high concurrency, the performance of synchronized will rapidly decline dozens of times, while the performance of ReentrantLock can still maintain the same level.

three。 Semaphore

1. Introduction

Semaphore (semaphore), which is used for current limiting processing. Is a counter that protects access to one or more shared resources. If a thread wants to access a resource, it must first get a semaphore. If the semaphore internal counter is greater than 0, the semaphore minus 1, and then allows the resource to be shared; otherwise, if the semaphore counter equals 0, the semaphore will put the thread into sleep until the counter is greater than 0. When the semaphore is used up, it must be released.

two。 Mode of use

Case: only five or five people are allowed to visit at the same time, and more than five people need to wait. For a requirement like this, the following case shows that the execution is the execution of five and five, and the next one will not be executed until the last one is finished.

Import java.util.concurrent.ExecutorService

Import java.util.concurrent.Executors

Import java.util.concurrent.Semaphore

Public class UseSemaphore {

Public static void main (String [] args) {

/ / Thread pool

ExecutorService exec = Executors.newCachedThreadPool ()

/ / only 5 threads can access it at the same time

Final Semaphore semp = new Semaphore (5)

/ / simulate 20 client accesses

For (int index = 0; index < 20; index++) {

Final int NO = index

Runnable run = new Runnable () {

Public void run () {

Try {

/ / obtain a license

Semp.acquire ()

System.out.println ("Accessing:" + NO)

/ / simulate the actual business logic

Thread.sleep ((long) (Math.random () * 10000))

/ / after the visit, release

Semp.release ()

} catch (InterruptedException e) {

}

}

}

Exec.execute (run)

}

Try {

Thread.sleep (10)

} catch (InterruptedException e) {

E.printStackTrace ()

}

/ / System.out.println (semp.getQueueLength ())

/ / exit thread pool

Exec.shutdown ()

}

}

3. Features and usage scenarios

A facility used in a multithreaded environment that coordinates threads to ensure their correct and rational use of common resources. Use scenarios such as in actual complex multithreaded applications, there may be multiple critical resources, at this time we can use Semaphore semaphores to complete the access of multiple critical resources.

four。 AtomicInteger

1. Introduction

AtomicInteger is an unlocked thread-safe integer, a class that provides Integer for atomic operations. In the Java language, + + I and iTunes + operations are not thread-safe, and the synchronized keyword is inevitably used when using them. AtomicInteger, on the other hand, uses a thread-safe addition and subtraction interface. (note: AtomicInteger is one of a series of similar representatives, such as AtomicLong, AtomicLong, etc., whose implementation principles are the same, but different from the types of operands.)

two。 Performance

According to the relevant data, the performance of AtomicInteger is usually several times that of ReentantLock.

Thank you for your reading, the above is the content of "what are the characteristics of the four common locks of java threads". After the study of this article, I believe you have a deeper understanding of what are the characteristics of the four common locks of Java threads, 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