# 死锁排查
# 死锁案例
import java.util.concurrent.TimeUnit;
@Slf4j
public class Demo {
public static void main(String[] args) throws InterruptedException {
Object a = new Object();
Object b = new Object();
new Thread(() -> {
synchronized (a) {
log.info("获取到A");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (b) {
log.info("获取到b");
}
}
}).start();
new Thread(() -> {
synchronized (b) {
log.info("获取到B");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (a) {
log.info("获取到A");
}
}
}).start();
}
}
# jstack
- jps 查看所有进程id
- jstack
jstack 6952
# 活锁
解决办法就是将时间错开
@Slf4j
public class Demo {
static volatile int count = 10;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
while (count < 20) {
count++;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("{}", count);
}
}, "t1").start();
new Thread(() -> {
while (count > 0) {
count--;
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.info("{}", count);
}
}, "t2").start();
}
}