当前位置:网站首页>Advanced concurrent programming series 9 (lock interface analysis)
Advanced concurrent programming series 9 (lock interface analysis)
2020-11-07 18:55:51 【yhhitall】
1. Test you
A lot of friends are getting started java In concurrent programming , When it comes to thread safety control , It must be right synchronized Key words are very familiar .synchronized Keyword means synchronous locking , I'm using , You have to wait until I'm finished .
For example Advanced Concurrent Programming Series 7 ( Introduction to lock ) This article , We are right. add_i Variable increment operation , Synchronous locking is the same , Give Way add_i Variables at the same time , It will only be operated by one thread , So thread safety .
/**
* addI Method , Realization add_i Variables operate on themselves
*/
public synchronized static void addI(){
add_i ++;
}
So to speak , You may have questions : since synchronized Keywords can be locked , Ensure thread safety . that java Why did the designer of juc The lock interface is provided in the package Lock, as well as Lock How about the implementation of the interface ? It's not just Yoga 、 He Shengliang ? Not good. , Do you want to repeat the story of Zhou Yu and Kong Ming !
It's not , Although there are synchronized keyword , We said there would be more Lock Interfaces and implementations are not redundant , So, let's talk about it together .
The reason why there is synchronized keyword , We need to provide Lock Interface , It is mainly based on the following factors :
-
synchronized Synchronous locking is internally controlled by jdk control , Fair lock . Practical application , Sometimes we need fair locks , But it can't . One sentence summary : inflexible
-
synchronized Synchronous locking is internally controlled by jdk control , Non interruptible . It's more domineering to use , Once the thread that acquired the lock is not finished , The outside can't be manipulated , Non interruptible lock acquisition thread . One sentence summary : inflexible
-
synchronized Synchronous locking is internally controlled by jdk control , Unable to get lock status , It's a thread A After getting the lock , Then the thread that needs the same lock BCD Can only be blocked waiting , Not flexible enough to use . For example, you can't thread A After getting the lock , Threads B To try to get the lock , If the lock cannot be acquired , Threads B You can do something else , You don't have to wait here . One sentence summary : inflexible
You can see , To sum up, we are interested in synchronized The impression of keywords is : inflexible . Here we need to pay attention to , Some friends are talking about synchronized keyword , And Lock When the lock is different , From the perspective of performance , In fact, from jdk1.6 in the future ,jvm Lock optimization is implemented internally , There is almost no difference in performance between the two . The main difference is still synchronized inflexible .
Then let's take a look at , in the light of synchronized Inflexible places ,Lock What solutions does the interface provide :
-
synchronized Lock is unfair lock .Lock Interface common implementation class ReentrantLock, When constructing a lock object , We can specify to construct fair locks , Or unfair lock , Implement on-demand construction
-
synchronized A lock is a non interruptible lock .Lock The interface provides lockInterruptibly() Method , Support interrupt operation
-
synchronized Lock cannot be locked .Lock The interface provides tryLock() Method , Used to return the lock state . If the thread A Lock has been acquired , So thread B adopt tryLock Attempt to acquire lock , You don't need to be blocked
-
in addition Lock Implementation class of interface , Through the read-write lock ReentrantReadWriteLock Read lock in class ReadLock, The shared lock is implemented . The so-called shared lock read lock , That is, everyone is reading operation , Don't be too outspoken , You can read , I can read , Reading is the real reading .
Through the above about Lock Description of the interface , Are you more and more in love with Lock Lock the interface , Yes, I think it is . So next , Let's see Lock Interface design , And basic usage .
2. Case study
2.1.Lock Interface source code
Through the analysis above , I think we'll all be curious ,Lock How the interface is designed , What capabilities does it need to provide us ? Right , Let's try to think about it :
-
Need a lock operation , So there should be a way to lock :lock
-
When the task is completed , A lock release operation is required , So there should be a way to release the lock :unlock
-
According to our above and synchronized contrast ,Lock Need to support getting lock state , If an attempt to acquire a lock fails , No need to block threads , So there should be an attempt to acquire a lock method :tryLock
-
According to our above and synchronized contrast ,Lock Interrupt operations need to support , Therefore, there should be a lock method that supports interrupt operations :lockInterruptibly
-
The above should be what we can intuitively think of Lock Basic ability , in fact Lock Interfaces are implemented through different implementation classes , Provides more powerful capabilities . We will gradually show through the case , For the moment, you don't need to care too much about
Let's take a look ,Lock Interface source screenshot , Besides looking at the pictures , I suggest you open jdk Source code , Have a look Lock Interface source code , There are very detailed source code comments , It's a great way to learn .
2.2.Lock Interface programming templates
In your application , If it's through synchronized Keyword lock words , You must still have an impression : Use synchronized keyword , We don't need to release the lock , Everything has jvm To control .
But if you choose a more flexible Lock Lock mode , Remember to : Matching release lock operation , Don't just give birth to 、 If you don't care about it, it's troublesome , So what's waiting for you is deadLock( Deadlock ) 了 .
Next, I'll give you a generic Lock Locks use templates , You need to pay attention to try{...}finally{...} Sentence block .
Here we will not expand the actual use case for the moment , Practical application cases , We'll put it in the next one to learn with you .
/**
* addI Method , Realization add_i Variables operate on themselves
* adopt Lock Lock
*/
public static void addI(){
// Lock
lock.lock();
try{
// Business operations
add_i ++;
}finally{
// Release the lock
lock.unlock();
}
}
版权声明
本文为[yhhitall]所创,转载请带上原文链接,感谢
边栏推荐
- C++ 数字、string和char*的转换
- C++学习——centos7上部署C++开发环境
- C++学习——一步步学会写Makefile
- C++学习——临时对象的产生与优化
- C++学习——对象的引用的用法
- C++编程经验(6):使用C++风格的类型转换
- Won the CKA + CKS certificate with the highest gold content in kubernetes in 31 days!
- C + + number, string and char * conversion
- C + + Learning -- capacity() and resize() in C + +
- C + + Learning -- about code performance optimization
猜你喜欢
-
C + + programming experience (6): using C + + style type conversion
-
Latest party and government work report ppt - Park ppt
-
在线身份证号码提取生日工具
-
Online ID number extraction birthday tool
-
️野指针?悬空指针?️ 一文带你搞懂!
-
Field pointer? Dangling pointer? This article will help you understand!
-
HCNA Routing&Switching之GVRP
-
GVRP of hcna Routing & Switching
-
Seq2Seq实现闲聊机器人
-
【闲聊机器人】seq2seq模型的原理
随机推荐
- LeetCode 91. 解码方法
- Seq2seq implements chat robot
- [chat robot] principle of seq2seq model
- Leetcode 91. Decoding method
- HCNA Routing&Switching之GVRP
- GVRP of hcna Routing & Switching
- HDU7016 Random Walk 2
- [Code+#1]Yazid 的新生舞会
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- HDU7016 Random Walk 2
- [code + 1] Yazid's freshman ball
- CF1548C The Three Little Pigs
- HDU7033 Typing Contest
- Qt Creator 自动补齐变慢的解决
- HALCON 20.11:如何处理标定助手品质问题
- HALCON 20.11:标定助手使用注意事项
- Solution of QT creator's automatic replenishment slowing down
- Halcon 20.11: how to deal with the quality problem of calibration assistant
- Halcon 20.11: precautions for use of calibration assistant
- “十大科学技术问题”揭晓!|青年科学家50²论坛
- "Top ten scientific and technological issues" announced| Young scientists 50 ² forum
- 求反转链表
- Reverse linked list
- js的数据类型
- JS data type
- 记一次文件读写遇到的bug
- Remember the bug encountered in reading and writing a file
- 单例模式
- Singleton mode
- 在这个 N 多编程语言争霸的世界,C++ 究竟还有没有未来?
- In this world of N programming languages, is there a future for C + +?
- es6模板字符
- js Promise
- js 数组方法 回顾
- ES6 template characters
- js Promise
- JS array method review
- 【Golang】️走进 Go 语言️ 第一课 Hello World
- [golang] go into go language lesson 1 Hello World