当前位置:网站首页>Lock锁
Lock锁
2022-04-23 16:53:00 【木十一的木马】
先看官方文档:

实现类有可重入锁、读锁和写锁,可重入锁最常用。
可重入锁,指的是以线程为单位,当一个线程获取对象锁之后,这个线程可以再次获取本对象上的锁,而其他的线程是不可以的。

可以看到,ReentrantLock是lock接口的一个实现类,里面实现了可重入锁和公平锁非公平锁。
公平锁:十分的公平,先来后到。
非公平锁:十分不公平,可以插队。
默认实现的是非公平锁。

它的整个逻辑就是:加锁,在try里写业务代码,在finally里解锁。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/** * @author DB * @title: Test02 * @projectName Juc * @description: TODO * @date 2022/4/21 10:34 */
public class Test02 {
public static void main(String[] args) {
Ticket2 ticket2 = new Ticket2();
new Thread(() -> {
for (int i = 0; i < 40; i ++)ticket2.sale();}, "A").start();
new Thread(() -> {
for (int i = 0; i < 40; i ++)ticket2.sale();}, "B").start();
new Thread(() -> {
for (int i = 0; i < 40; i ++)ticket2.sale();}, "C").start();
}
}
class Ticket2 {
//属性
private int number = 30;
Lock lock = new ReentrantLock();
//方法
public synchronized void sale(){
//加锁
lock.lock();
try {
//写业务代码
if (number > 0){
System.out.println(Thread.currentThread().getName() + "卖出了" + (number --) + "票,剩余" + number);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//解锁
lock.unlock();
}
}
}
结果:

Synchronized和Lock的区别?
(1)Synchronized 是Java的内置关键字;Lock是一个Java类。
(2)Synchronized 无法判断获取锁的状态;Lock可以判断是否获取到了锁。
(3)Synchronized 会自动释放锁;lock必须手动释放锁,如果不释放->死锁。
(4)Synchronized 线程1(获得锁,阻塞),线程2(等待,傻傻的等);lock锁不一定会等。
(5)Synchronized 可重入锁,不可以中断的,非公平锁;Lock锁,可重入锁,可以判断,自己可以设置公平还是非公平。
(6)Synchronized 适合锁少量的代码同步问题;Lock适合锁大量的同步代码。
版权声明
本文为[木十一的木马]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_49005459/article/details/124315927
边栏推荐
- Calculate pie chart percentage
- Talk about browser cache control
- Node access to Alipay open platform sandbox to achieve payment function
- Multithreaded @ async thread pool
- 如何用Redis实现分布式锁?
- LVM and disk quota
- File upload and download of robot framework
- ∑GL-透视投影矩阵的推导
- 拷贝构造函数 浅拷贝与深拷贝
- Nacos detailed explanation, something
猜你喜欢

Kunteng full duplex digital wireless transceiver chip kt1605 / kt1606 / kt1607 / kt1608 is suitable for interphone scheme

How to choose the wireless gooseneck anchor microphone and handheld microphone scheme

Use if else to judge in sail software - use the title condition to judge

Pytorch: the pit between train mode and eval mode

信息摘要、数字签名、数字证书、对称加密与非对称加密详解

英语 | Day15、16 x 句句真研每日一句(从句断开、修饰)

DanceNN:字节自研千亿级规模文件元数据存储系统概述

How vscode compares the similarities and differences between two files

Bytevcharts visual chart library, I have everything you want

Take according to the actual situation, classify and summarize once every three levels, and see the figure to know the demand
随机推荐
Query the data from 2013 to 2021, and only query the data from 2020. The solution to this problem is carried out
Rtklib 2.4.3 source code Notes
Deeply understand the relevant knowledge of 3D model (modeling, material mapping, UV, normal), and the difference between displacement mapping, bump mapping and normal mapping
Zhimeng dedecms security setup Guide
File system read and write performance test practice
NVIDIA graphics card driver error
Derivation of Σ GL perspective projection matrix
Flask如何在内存中缓存数据?
Project framework of robot framework
∑GL-透视投影矩阵的推导
100 deep learning cases | day 41 - convolutional neural network (CNN): urbansound 8K audio classification (speech recognition)
Idea of batch manufacturing test data, with source code
Camtasia2022软件新增功能介绍
[pimf] openharmony paper Club - what is the experience of wandering in ACM survey
org. apache. parquet. schema. InvalidSchemaException: A group type can not be empty. Parquet does not su
5-minute NLP: text to text transfer transformer (T5) unified text to text task model
DanceNN:字节自研千亿级规模文件元数据存储系统概述
5分钟NLP:Text-To-Text Transfer Transformer (T5)统一的文本到文本任务模型
About background image gradient()!
How to implement distributed locks with redis?