说明:先上代码,笔记后续补充。
public class LockTest1 {
/**
* 锁嵌套会出现死锁
* 避免 1.尽量不要写锁的嵌套(约等于废话,因为写了嵌套那么肯定是需要它) 2.锁嵌套的顺序(都调用getLock方法) 3.引入超时机制
*/
//显示锁Lock,可重入锁
//可中断锁,Lock就是,可以中断的
//公平锁,synchronized是随机锁,不公平
//乐观锁,悲观锁 数据库层面
Lock lock = new ReentrantLock();
/**
* 读 上readerLock 写上WriteLock
*/
ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//锁 locka lockb
private Object locka = new Object();
private Object lockb = new Object();
public static void main(String[] args) {
new LockTest1().deadLock();
}
/**
* 嵌套锁
*/
private void deadLock(){
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
getLock();
// synchronized (locka){
// try {
// System.out.println(Thread.currentThread().getName()+"获取A锁!");
// Thread.sleep(500);
// System.out.println(Thread.currentThread().getName()+"睡眠500ms");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"需要B锁");
// synchronized (lockb){
// System.out.println(Thread.currentThread().getName()+"B锁中!");
// }
// }
}
},"thread1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
getLock();
// synchronized (lockb){
// try {
// System.out.println(Thread.currentThread().getName()+"获取B锁!");
// Thread.sleep(500);
// System.out.println(Thread.currentThread().getName()+"睡眠500ms");
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// System.out.println(Thread.currentThread().getName()+"需要A锁");
// synchronized (locka){
// System.out.println(Thread.currentThread().getName()+"A锁中!");
// }
// }
}
},"thread2");
thread1.start();
thread2.start();
}
public void getLock(){
synchronized (locka){
try {
System.out.println(Thread.currentThread().getName()+"获取A锁!");
Thread.sleep(500);
System.out.println(Thread.currentThread().getName()+"睡眠500ms");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"需要B锁");
synchronized (lockb){
System.out.println(Thread.currentThread().getName()+"B锁中!");
}
}
}
}
Lock 显式锁 是一个接口,其中主要包含以下几个方法
获取锁:lock() lockInterruptibly() tryLock()
释放锁:unlock()
转载于:https://www.cnblogs.com/sleepy-goblin/p/8910052.html