当前位置:网站首页>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
边栏推荐
- Implementation steps of dynamic proxy
- Myrpc version 1
- (03). Net Maui actual combat basic control
- Slam mapping, automatic navigation and obstacle avoidance based on ROS (bingda robot)
- 2021-11-04
- Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0
- 在大厂外包呆了三年,颠覆了我的认知!
- (04). Net Maui actual MVVM
- mysql更新数组形式的json串
- Five methods to clear floating and their advantages and disadvantages
猜你喜欢

lego_loam 代码阅读与总结

The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database

第十一天 脚本与游戏AI

lego_ Reading and summary of loam code

Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0

Day 10 data saving and loading

With the deep integration of cloud platform, the "Xueba" objectscale in the object storage industry is coming

Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain

dotnet-exec 0.5.0 released

Slam mapping, automatic navigation and obstacle avoidance based on ROS (bingda robot)
随机推荐
Junior students summarize JS advanced interview questions
Memorize unfamiliar words at SSM stage and update them from time to time
Educoder group purchase suspension box page production
SQLyog导入数据库时报错,求帮解决!
Es2018 key summary
基于ROS的SLAM建图、自动导航、避障(冰达机器人)
iMile 利用 Zadig 多云环境周部署千次,跨云跨地域持续交付全球业务
DBT product initial experience
internship:接口案例实现
[从零开始学习FPGA编程-52]:高阶篇 - 基于IP核的FPGA开发 - IP核使用的基本框架(以锁相环PLL为例)
第十天 数据的保存与加载
Jour 9 Gestion des scripts et des ressources
JS inheritance
lego_loam 代码阅读与总结
JS static method
2021-11-04
Quick sort & merge sort
[learn FPGA programming from scratch -52]: high level chapter - FPGA development based on IP core - basic framework for IP core use (taking PLL as an example)
dotnet-exec 0.5.0 released
The new paradigm of AI landing is "hidden" in the next major upgrade of software infrastructure