当前位置:网站首页>What is the difference between synchronized and lock
What is the difference between synchronized and lock
2022-06-30 04:22:00 【No bug program yuan】
subject :synchronized and Lock What's the difference? ? With the new Lock What are the benefits ? For example
1. Original composition
synchronized Yes, the keyword belongs to JVW level ,
monitorenter( The bottom is through monitor Object to complete , Actually wait/notify And so on monitor Objects can only be called in synchronous blocks or methods wait/notify Other methods ,
lock It's a concrete class (java.util.concurrent.locks.Lock) yes api Level lock
2. Usage method
synchronized There is no need for the user to release the lock manually , When synchronized After the code is executed, the system will automatically let the thread release the lock occupation
ReentrantLock You need to manually release the lock , If there is no active release lock , May cause Deadlock
3. Whether waiting can be interrupted
synchronized Non interruptible , Unless an exception is thrown or normal operation is completed
ReentrantLock interruptible ,1. No timeout method is set tryLock(long timeout,Timeunit unit)
2.LockIterruptiblyo Put it in the code block , Tiaochuan interrupt() Method can be interrupted
4. Is it fair to lock
synchronized Not fair lock
ReentrantLock Either way , Default unfair lock , The constructor can pass in boolean value ,ture Lock for fairness ,false Lock for unfairness
5. Lock binding multiple conditions condition
synchronized No,
ReentrantLock Threads used to wake up packets , Can wake up exactly , Not like it synchronized Either wake up one thread randomly or wake up all threads .
Precise wake-up sample code :
class MyData{
private int number=1; // A B C
private Lock lock=new ReentrantLock();
private Condition c1=lock.newCondition();
private Condition c2=lock.newCondition();
private Condition c3=lock.newCondition();
public void print1(){
lock.lock();
try {
//1 Judge
while (number!=1){
c1.await();
}
//2 work
for (int i = 1; i <=1 ; i++) {
System.out.println(Thread.currentThread().getName()+"\t"+i);
}
//3 notice
number=2;
c2.signal(); // Notify the next thread
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print2(){
lock.lock();
try {
//1 Judge
while (number!=2){
c2.await();
}
//2 work
for (int i = 1; i <=2 ; i++) {
System.out.println(Thread.currentThread().getName()+"\t"+i);
}
//3 notice
number=3;
c3.signal(); // Notify the next thread
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print3(){
lock.lock();
try {
//1 Judge
while (number!=3){
c3.await();
}
//2 work
for (int i = 1; i <=3 ; i++) {
System.out.println(Thread.currentThread().getName()+"\t"+i);
}
//3 notice
number=1;
c1.signal(); // Notify the next thread
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
MyData myData=new MyData();
new Thread(()->{
for(int i=1;i<=3;i++){
myData.print1();
}
},"A").start();
new Thread(()->{
for(int i=1;i<=3;i++){
myData.print2();
}
},"B").start();
new Thread(()->{
for(int i=1;i<=3;i++){
myData.print3();
}
},"C").start();
}
}
// Execution results
A 1
B 1
B 2
C 1
C 2
C 3
A 1
B 1
B 2
C 1
C 2
C 3
A 1
B 1
B 2
C 1
C 2
C 3
边栏推荐
- FortiGate creates multiple corresponding DDNS dynamic domain names for multiple ADSL interfaces
- How to solve the problem of link hyperlinks when trying to link the database?
- FortiGate firewall quick initialization administrator password
- 深度融合云平台,对象存储界的“学霸”ObjectScale来了
- FortiGate configures multiple server IPS as link monitor monitoring objects on the same interface
- Qt Creator 8 Beta2发布
- RPC correction based on arcpy API
- Five methods to clear floating and their advantages and disadvantages
- 基于SSM框架茶叶商城系统【项目源码+数据库脚本+报告】
- Share an example of a simple MapReduce method using a virtual machine
猜你喜欢
Troubleshoot abnormal video playback problems in public network deployment based on Haikang ehomedemo tool
Matlab reads fig file and restores signal
Sql语句遇到的错误,求解
Myrpc version 6
Blue Bridge Cup: magic cube rotation [Vocational group]
El upload Upload file (Manual upload, Automatic upload, upload progress)
Day 9 script and resource management
[fuzzy neural network prediction] water quality prediction based on fuzzy neural network, including Matlab source code
El upload upload file (manual upload, automatic upload, upload progress)
Share an example of a simple MapReduce method using a virtual machine
随机推荐
Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain
Five methods to clear floating and their advantages and disadvantages
DBT product initial experience
第十天 数据的保存与加载
Find the interface and add parameters to the form
oslo_ config. cfg. ConfigFileParseError: Failed to parse /etc/glance/glance-api. Conf: a solution to errors
基于SSM框架茶叶商城系统【项目源码+数据库脚本+报告】
SQL append field
lego_ Reading and summary of loam code
SQLyog导入数据库时报错,求帮解决!
Basic knowledge of redis
FortiGate performs DNAT mapping, and intranet users cannot normally access the mapping
JS inheritance
Interface testing -- how to analyze an interface?
You know AI, database and computer system
Myrpc version 3
El upload Upload file (Manual upload, Automatic upload, upload progress)
网络层详解
Day 10 data saving and loading
iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务