公平锁:非常公平,线程不能插队 非公平锁,线程可以插队 Lock lock = new ReentrantLock();就是非公平锁
同步方法嵌套,线程在拿到外边锁了,也会获取到里边的锁,
synchronized锁
public class Demo1 { public static void main(String[] args) { Phone phone = new Phone(); new Thread(()->{ phone.send(); },"a").start(); new Thread(()->{ phone.send(); },"b").start(); } } class Phone{ public synchronized void send(){ System.out.println(Thread.currentThread().getName() + "---send"); call(); } public synchronized void call(){ System.out.println(Thread.currentThread().getName() + "----call"); } }Lock锁
public class Demo1 { public static void main(String[] args) { Phone phone = new Phone(); new Thread(()->{ phone.send(); },"a").start(); new Thread(()->{ phone.send(); },"b").start(); } } class Phone{ Lock lock = new ReentrantLock(); public void send(){ lock.lock(); try { System.out.println(Thread.currentThread().getName() + "---send"); call(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } public void call(){ lock.lock(); try { System.out.println(Thread.currentThread().getName() + "----call"); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }查看死锁 在死锁情况下,idea的Terminal窗口
idea的Terminal窗口输入jps -l ,查询进程号 然后在输入:jstack 进程号 信息拉到最下边就可以看到死锁的信息
