指的是以线程为单位,当一个线程获取对象锁之后,这个线程可以再次获取本对象上的锁,而其他的线程是不可以的。
public class ReenterLockTest { public static void main(String[] args) { new Thread(()->{ reenterLock_DaMen(); }).start(); new Thread(()->{ reenterLock_DaMen(); }).start(); } private static void reenterLock_DaMen() { synchronized (ReenterLockTest_Phone.class){ System.out.println(Thread.currentThread().getName()+"打开大门"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } reenterLock_room(); } } private static void reenterLock_room() { synchronized (ReenterLockTest_Phone.class){ System.out.println(Thread.currentThread().getName()+"打开房间门"); } } }
循环会耗时
只能一个自变量的原子性
ABA
package com.fh.thread.locks.spinlock; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public class SpinLockTest { public static void main(String[] args) { SpinLock spinLock = new SpinLock(); new Thread(()->{ try { spinLock.lock(); TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }finally { spinLock.unlock(); } },"t1").start(); new Thread(()->{ try { spinLock.lock(); TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }finally { spinLock.unlock(); } },"t2").start(); } } class SpinLock{ private AtomicReference<Thread> atomicReference = new AtomicReference<>(); public void lock(){ Thread thread = Thread.currentThread(); System.out.println(thread.getName()+"加锁"); while (!atomicReference.compareAndSet(null,thread)){ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(thread.getName()+"自旋吧。。。"); } } public void unlock(){ Thread thread = Thread.currentThread(); System.out.println(thread.getName()+"解锁"); atomicReference.compareAndSet(thread,null); } }
死锁
乐观锁
悲观锁