(无语死了,这破显示字体,一直是小的)
synchronized和lock默认是非公平锁,为了优化速度假如:
A线程需要3s执行完毕,B线程需要1H,肯定先执行A。
lock只需要在构造方法传入true就是公平锁
Lock lock=new ReentrantLock(true)
可重复锁则是在锁里面还可以再获取锁(就是递归思想),依次解锁释放
自旋锁就有点流弊了,通过对锁的判断状态,进行自旋:(我也不知道为啥,我用自己一直实现不了,用原子类就可以)
javapackage com.quxiao.entity; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class MyLock { AtomicInteger atomicInteger = new AtomicInteger(); public void lock() { //上一个取到锁,赋值为1,释放锁时调用unlock,赋值为0,结束下一个线程的自旋 while (!atomicInteger.compareAndSet(0, 1)) { } } public void unlock() { //释放锁 atomicInteger.compareAndSet(1, 0); } }
死锁:A等B,B等A(好凄凉,哈哈哈哈哈哈)
javapackage com.quxiao.controller; import com.quxiao.entity.MyLock; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @program: package1 * @author: quxiao * @create: 2023-09-27 15:22 **/ public class t3 { public static void main(String[] args) { final String a = "1"; final String b = "2"; new Thread(() -> { try { new t(a, b); } catch (InterruptedException e) { throw new RuntimeException(e); } }, "A").start(); new Thread(() -> { try { new t(b, a); } catch (InterruptedException e) { throw new RuntimeException(e); } }, "B").start(); } static class t { public t(String a, String b) throws InterruptedException { synchronized (a) { System.out.println(Thread.currentThread().getName() + "a"); TimeUnit.SECONDS.sleep(2); synchronized (b) { System.out.println(Thread.currentThread().getName() + "b"); } } } } }
排查办法:
控制台查看进程:
jps -l
然后使用jstack [进程号]