//死锁实例:
@AllArgsConstructor
@Data
class MyRunnable implements Runnable{
private String lockA;
private String lockB;
@Override
public void run() {
synchronized (lockA){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("获得锁"+lockA+",尝试获取"+lockB);
synchronized (lockB){
System.out.println("已经尝试获得锁"+lockB);
}
}
}
}
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new MyRunnable(lockA,lockB)).start();
new Thread(new MyRunnable(lockB,lockA)).start();
}
活锁
/** * 活锁 * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { ReentrantLock A = new ReentrantLock(); ReentrantLock B = new ReentrantLock(); new Thread(() -> { boolean noOkflag = true; while (noOkflag) { if (A.tryLock()){ System.out.println(Thread.currentThread()+"成功获取锁A"); } if (B.tryLock()) { System.out.println(Thread.currentThread()+"====================成功获取锁B"); B.unlock(); noOkflag = false; } if (A.isLocked()) { A.unlock(); } } }).start(); new Thread(() -> { boolean noOkflag = true; while (noOkflag) { if (B.tryLock()) { System.out.println(Thread.currentThread() + "成功获取锁B"); } if (A.tryLock()) { System.out.println(Thread.currentThread() + "=====================成功获取锁A"); A.unlock(); noOkflag = false; } if (B.isLocked()) { B.unlock(); } } }).start(); }