三、Lock鎖 (重點)
傳統 Synchronized 相當于排隊,佇列
超賣問題
耦合性: 判斷代碼模塊構成質量的屬性,不影響已有功能,但影響未來拓展
? 耦合性越強,模塊之間的聯系越緊密,但獨立性越差
高內聚 低耦合!
Lock 介面

實作類:
- ReentrantLock 可重入鎖 常用
- ReentranReadWritetLock.ReadLock 讀鎖
- ReentranReadWritetLock.WriteLock 寫鎖
公平鎖 vs 非公平鎖

公平鎖: 絕對公平 可以先來后到
非公平鎖:不公平 ,可以插隊(默認非公平鎖)CPU調度 耗時少的執行緒優先
Lock 三部曲:
-
- Lock lock = new ReentrantLock();
-
- lock.lock();
-
- finally => lock.unlock();
package com.liu.demo01;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SafeTicketDemo02 {
public static void main(String[] args) {
// 并發: 多執行緒操作同一個資源 把資源類丟入執行緒
Ticket02 ticket = new Ticket02();
// 函式式介面 FunctionalInterface jdk1.8 lambda運算式
// (引數) -> {代碼邏輯}
new Thread(() -> {
for (int i = 0; i < 40; i++) ticket.sale();
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 40; i++) ticket.sale();
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 40; i++) ticket.sale();
}, "C").start();
}
}
//資源類 OOP 避免和執行緒耦合 降低耦合性 耦合性
class Ticket02 {
// 屬性 、方法
private int nums = 50;
// lock
Lock lock = new ReentrantLock();
// 賣票方式
public void sale() {
lock.lock(); // 加鎖
try {
//核心業務邏輯代碼
if (nums > 0) {
System.out.println(Thread.currentThread().getName() + "賣出了第" + nums-- + "張票!" + ",剩余" + nums + "張票");
}
} finally {
lock.unlock(); // 解鎖
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/289081.html
標籤:其他
上一篇:【Git】pull遇到錯誤:error: Your local changes to the following files would be overwritten by merge:
