JavaSE---多线程---锁---Lock
1、ReentrantLock
1.1、可重入锁: 当 某个线程获得到某个锁,可以重复获取相同的锁 而不会 出现死锁;
1.2、可重入锁: synchronized、ReentrantLock
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | package com.an.lock.reentrantlocks; /** * @description: * @author: anpeiyong * @date: Created in 2020/6/10 13:51 * @since: */ public class SynchronizedTest { public static void main(String[] args) { new Thread( new Runnable() { @Override public void run() { synchronized ( this ) { System.out.println( "第1次获取锁,这个锁是:" + this ); int index = 1 ; while ( true ) { synchronized ( this ) { System.out.println( "第" + (++index) + "次获取锁,这个锁是:" + this ); } if (index == 10 ) { break ; } } } } }).start(); } } 结果: 第 1 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 2 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 3 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 4 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 5 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 6 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 7 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 8 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 9 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d 第 10 次获取锁,这个锁是:com.an.lock.reentrantlocks.SynchronizedTest$ 1 @d7f994d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | package com.an.lock.reentrantlocks; import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @description: 获取锁、释放锁 需要匹配 * @author: anpeiyong * @date: Created in 2020/6/10 13:53 * @since: */ public class LockTest { public static void main(String[] args) { Lock lock = new ReentrantLock(); new Thread( new Runnable() { @Override public void run() { try { lock.lock(); System.out.println( "第1次获取锁,这个锁是:" + lock); int index = 1 ; while ( true ) { try { lock.lock(); System.out.println( "第" + (++index) + "次获取锁,这个锁是:" + lock); try { Thread.sleep( new Random().nextInt( 200 )); } catch (InterruptedException e) { e.printStackTrace(); } if (index == 10 ) { break ; } } finally { lock.unlock(); } } } finally { lock.unlock(); } } }).start(); } } 结果: 第 1 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 2 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 3 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 4 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 5 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 6 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 7 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 8 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 9 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] 第 10 次获取锁,这个锁是:java.util.concurrent.locks.ReentrantLock @570ead58 [Locked by thread Thread- 0 ] |
1.3、ReentrantLock
1.4、ReentrantLock内部类Sync
1.5、AbstractQueuedSynchronizer
组成:volatile修饰的state + 双向链表
实现:
自旋 、CAS 、LockSupport.park()|unpark()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable { private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long stateOffset; private static final long headOffset; private static final long tailOffset; private static final long waitStatusOffset; private static final long nextOffset; static { try { stateOffset = unsafe.objectFieldOffset (AbstractQueuedSynchronizer. class .getDeclaredField( "state" )); headOffset = unsafe.objectFieldOffset (AbstractQueuedSynchronizer. class .getDeclaredField( "head" )); tailOffset = unsafe.objectFieldOffset (AbstractQueuedSynchronizer. class .getDeclaredField( "tail" )); waitStatusOffset = unsafe.objectFieldOffset (Node. class .getDeclaredField( "waitStatus" )); nextOffset = unsafe.objectFieldOffset (Node. class .getDeclaredField( "next" )); } catch (Exception ex) { throw new Error(ex); } } static final class Node { } private transient volatile Node head; private transient volatile Node tail; private volatile int state; //默认非公平锁 public ReentrantLock() { sync = new NonfairSync(); } public ReentrantLock( boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); } } |
2、ReentrantReadWriteLock
3、ReentrantLock的锁获取方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | public class ReentrantLock implements Lock, java.io.Serializable { private final Sync sync; public void lock() { sync.lock(); } abstract static class Sync extends AbstractQueuedSynchronizer { abstract void lock(); final boolean nonfairTryAcquire( int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0 ) { if (compareAndSetState( 0 , acquires)) { setExclusiveOwnerThread(current); return true ; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0 ) // overflow throw new Error( "Maximum lock count exceeded" ); setState(nextc); return true ; } return false ; } } static final class FairSync extends Sync { final void lock() { acquire( 1 ); } protected final boolean tryAcquire( int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0 ) { if (!hasQueuedPredecessors() && compareAndSetState( 0 , acquires)) { setExclusiveOwnerThread(current); return true ; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0 ) throw new Error( "Maximum lock count exceeded" ); setState(nextc); return true ; } return false ; } } static final class NonfairSync extends Sync { final void lock() { if (compareAndSetState( 0 , 1 )) setExclusiveOwnerThread(Thread.currentThread()); else acquire( 1 ); } protected final boolean tryAcquire( int acquires) { return nonfairTryAcquire(acquires); } } } public abstract class AbstractQueuedSynchronizer extends AbstractOwnableSynchronizer implements java.io.Serializable { public final void acquire( int arg) { //tryAcquire() acquireQueued() 轮询获取资源 if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //获取失败,当前线程中断 selfInterrupt(); } private Node addWaiter(Node mode) { Node node = new Node(Thread.currentThread(), mode); // 快速插入 Node pred = tail; if (pred != null ) { node.prev = pred; if (compareAndSetTail(pred, node)) { pred.next = node; return node; } } //常规插入 enq(node); return node; } private Node enq( final Node node) { for (;;) { Node t = tail; if (t == null ) { // Must initialize if (compareAndSetHead( new Node())) tail = head; } else { node.prev = t; if (compareAndSetTail(t, node)) { t.next = node; return t; } } } } final boolean acquireQueued( final Node node, int arg) { boolean failed = true ; try { boolean interrupted = false ; for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null ; // help GC failed = false ; return interrupted; } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true ; } } finally { if (failed) cancelAcquire(node); } } static void selfInterrupt() { Thread.currentThread().interrupt(); } } |
3.2、可轮询
4、公平性
按 线程之间 获取锁的顺序
4.1、公平锁:
线程 顺序请求锁;
4.2、非公平锁:
线程 只有 在锁被占用时等待,允许跳跃获得锁;
5、Lock与synchronized选择
5.1、只有 synchronized 不能满足(比如 可定时锁、公平锁、可中断锁 )使用时,才使用 Lock,否则,推荐synchronized ;
6、ReadWriteLock
6.1、一个资源 同时 被多个线程读取 且 只被一个线程写入;
6.2、读写锁能够提供更好的并发性;
7、ReentrantReadWriteLock
7.1、
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public interface ReadWriteLock { Lock readLock(); Lock writeLock(); } public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable { final Sync sync; abstract static class Sync extends AbstractQueuedSynchronizer {} static final class NonfairSync extends Sync {} static final class FairSync extends Sync {} public static class ReadLock implements Lock, java.io.Serializable {} public static class WriteLock implements Lock, java.io.Serializable {} } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2019-06-10 《编码》