死锁发生的原因:
是因为两个线程获取锁的顺序不一致,导致出现线程分别要获取对方持有的锁状况,程序无法继续运行;
解决死锁的一般逻辑:
1.修改获取锁的顺序;
2.缩小锁的范围
3.从业务角度解决
死锁代码示例
@Test
public void testDeadLock() throws InterruptedException {
Object lock1 = new Object();
Object lock2 = new Object();
new Thread(new DeadLockTask1(lock1,lock2),"A").start();
new Thread(new DeadLockTask2(lock1,lock2),"B").start();
Thread.sleep(100000);
}
static class DeadLockTask1 implements Runnable {
private Object lock1;
private Object lock2;
public DeadLockTask1(Object lock1, Object lock2) {
this.lock1 = lock1;
this.lock2 = lock2;
}
@Override
public void run() {
while (true) {
synchronized (lock1) {
synchronized (lock2) {
System.out.println(Thread.currentThread().getName() + ".....");
}
}
}
}
}
static class DeadLockTask2 implements Runnable {
private Object lock1;
private Object lock2;
public DeadLockTask2(Object lock1, Object lock2) {
this.lock1 = lock1;
this.lock2 = lock2;
}
@Override
public void run() {
while (true) {
synchronized (lock2) {
synchronized (lock1) {
System.out.println(Thread.currentThread().getName() + ".....");
}
}
}
}
}
第二类代码示例:(这个例子也证明synchronized是可重入锁)
@Test
public void testDeadLock2() throws InterruptedException {
DeadLockTask3 task = new DeadLockTask3();
new Thread(task,"A").start();
Thread.sleep(1000);
task.flag = false;
new Thread(task,"B").start();
Thread.sleep(100000);
}
static class DeadLockTask3 implements Runnable {
private Object lock = new Object();
volatile boolean flag = true;
@Override
public void run() {
if(flag) {
while(true)
synchronized (lock) {
show();
}
} else {
while(true)
show();
}
}
synchronized void show(){
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ".....");
}
}
}