当前位置:网站首页>Synchronized and reentrantlock
Synchronized and reentrantlock
2022-07-26 11:16:00 【qq_ five hundred and forty-seven million twenty-six thousand on】
1. Synchronized
- Lock concept :
Synchronized yes JVM Level lock , yes Java keyword , adopt monitor Object to complete . In execution monitorenter When the command , First try to get the object lock . If this object is not locked , Or the current thread already has the object lock , Add the lock calculator 1, Corresponding , In execution monitorexit When the command is given, the lock counter will be subtracted 1, When calculator is 0 when , The lock is released . If getting object lock fails , Then the current thread will be blocked , Until the object lock is released by another thread . - Lock type :
(1) Object lock : Including method locks ( The default lock object is this, That is, the current instance object ) And synchronization code block lock ( Specify the lock object by yourself ).
public synchronized void method(){} --> Method lock
Synchronized(object){} --> Synchronization code block
(2) Kind of lock : finger synchronized Keyword decorated static method or specified lock object is .class object .
public synchronized static void method(){} --> synchronized Add to the static method
Synchronized(*.class){} --> Lock object for class object
- The core idea :
(1) A lock can only be acquired by one thread at a time , Threads that do not get the lock must wait ;
(2) Each object has its own lock , The lock corresponding to the same object is the same lock , Different objects have different locks , Different locks can be acquired and executed by different threads at the same time . Except class lock , That is to say, all objects of the class corresponding to the class lock share this lock .( for example , The class corresponding to this class lock new Multiple objects cannot access this method at the same time );
(3) The lock will be released after the normal execution of the method or when the method throws an exception , and Lock But will not release the lock .
(4) If in a quilt synchronized The modified method calls the asynchronous method , Then this method is also thread unsafe .
(1). A lock can only be acquired by one thread at a time , Threads that do not get the lock must wait ; - Lock property :
(1) Reentrant : It refers to the lock obtained by the outer function of the same thread , The inner function can directly obtain the lock again , Reentrant granularity is threads, not scheduling . Its principle is mainly :jvm Responsible for tracking the number of times the object has been locked , When a thread acquires a lock for the first time , The count changes to 1, When this thread acquires the lock again , The count will increase , Every time the mission leaves , The count will decrease , When the count changes to 0 when , The lock is released completely .
(2) Waiting cannot be interrupted : Once the lock has been acquired by another thread , If other threads still want to get this lock , You can only choose to wait or block , Until that thread releases the lock . If that thread never releases that lock , Then other threads will wait forever .
(3) Unfair : It refers to multiple threads waiting for the same lock , There is no need to acquire locks in the order in which threads apply , All threads waiting for the lock acquire the lock randomly . - Advantages and disadvantages :
- advantage :
(1) Easy to use , Add synchronized Keywords are good .
(2) Do not release the lock manually , It can reduce the probability of deadlock . - shortcoming :
(1) Low efficiency , Less lock release , You cannot set a timeout when trying to acquire a lock , Cannot interrupt a thread that is trying to acquire a lock .
(2) inflexible , The timing of locking and releasing the lock is single , Each lock has a single condition ( An object ).
(3) It is impossible to know whether the lock was successfully acquired .
- advantage :
2. ReentrantLock
ReentrantLock yes java.util.concurrent A set of mutually exclusive locks provided under the package , Realized Lock The class of the interface , also ReentrantLock More ways .
- How locks are created :
Lock lock = new ReentrantLock(true);
Pass in... Through the construction method boolean Value , If it is empty, the default is false Not fair lock ,true Lock for fairness . therefore ReentrantLock Is a fair or unfair lock . - There are four ways to obtain locks :
(1)lock(): If the lock is acquired, return immediately , If another thread holds the lock , The current thread remains dormant , Until the lock is acquired .
(2)tryLock(): If the lock is acquired, return immediately true, If another thread is holding the lock , Return immediately false.
(3)tryLock(long timeout,TimeUnit unit): If you get a lock, return immediately true, If another thread is holding the lock , Will wait for the time given by the parameter , In the process of waiting , If you get the lock , Just go back to true, If the wait times out , return false.
(4)lockInterruptibly(): If the lock is acquired, return immediately , If another thread holds the lock , Then the current thread will interrupt the process of waiting to acquire the lock . - The lock needs to be released manually :
Generally in finally{} Call in block lock.unlock() Method to release the lock , If you don't release the lock , Then other threads will no longer be able to obtain the lock , It is easy to cause deadlock . - Lock property :
(1) Reentrant :ReentrantLock It literally means the lock of re-entry , There's not much difference between the two .
(2) Wait for interruptible : Provides a mechanism to interrupt threads waiting for locks , adopt lock.lockInterruptibly() To implement this mechanism . It can also be done through tryLock(long timeout,TimeUnit unit) The way , Set the waiting time , If it exceeds this length of time, it will automatically give up waiting .
(3) Fair enough : Pass in parameters through the constructor true, You can create a fair lock . When multiple threads wait for the same lock , Locks must be obtained in the order in which they were requested .
(4) Multiple conditions can be bound : It's in one Lock Object can create multiple Condition example ( Object monitor ), Thread objects can be registered in the specified Condition in , In this way, thread notification can be carried out selectively , More flexible on scheduling threads . and synchronized Keywords are equivalent to the whole Lock There is only one object Condition example , All threads are registered in one Condition On the body . If you execute notifyAll() Method will notify all threads in the waiting state, which will cause great efficiency problems , and Condition Example of signalAll() Method Will only wake up registration in this Condition All waiting threads in the instance . - Advantages and disadvantages :
- advantage :
(1) Efficient , Waiting time can be set , Don't spend a lot of time waiting for the lock .
(2) Flexible use , You can call the code you want to synchronize lock() Method gets the lock , Multiple conditions can be bound , Thread notification can be performed selectively .
(3) You can view the status of the lock , Is the lock locked . - shortcoming :
(1) Manual call required unlock() Method release lock .
(2) It's easy to cause deadlock .
- advantage :
边栏推荐
- ORBSLAM2 CmakeLists文件结构解析
- QT——连接USB摄像头
- There is an unhandled exception at 0x003b66c3 in MFC: 0xc000041d: unhandled exception encountered during user callback
- logging 高级使用
- MySQL锁机制
- UDF and analysis case of sparksql, 220725,
- Scrapy shell出现的一个错误
- Bash shell learning notes (I)
- 公司无法访问b站
- ISO 639:1988 : Code for the representation of names of languages
猜你喜欢
随机推荐
QT——LCDNumber
-bash: ./build.sh: /bin/bash^M: 坏的解释器: 没有那个文件或目录
承认吧 投新能源就是为了安全感
Leetcode-209. subarray with the smallest length (binary, prefix and, sliding window)
浅谈VIO之IMU预积分(还是刚入门时的想法)
pytest fixture装饰器
Drbl diskless startup + Clonezilla network backup and restore system
母亲
MySql基础知识汇总
Postman export import
Pyqt5 rapid development and practice 3.1 QT designer quick start
pytest pytest.ini配置 用例分组 用例跳过
Definition and use of C language namespace
UDF and analysis case of sparksql, 220725,
Pytest execution rules_ Basic usage_ Common plug-ins_ Common assertions_ Common parameters
pytest pytest. Ini configuration case grouping case skipping
Pytest fixture decorator
Basic use of logging
3dunity game project practice - first person shooting game
MySQL事务详解









