死锁小结
2019-06-14 本文已影响0人
枫叶忆
死锁
什么是死锁
两个或两个以上的线程在执行过程中,因为争夺资源而造成一种相互等待的现象
死锁的原因
系统资源不足
线程运行推进的顺序不合理
资源分配不当
手写死锁
package com.hz.xhf;
public class HoldLockThread implements Runnable {
private String lockA;
private String lockB;
public HoldLockThread(String lockA, String lockB) {
this.lockA = lockA;
this.lockB = lockB;
}
@Override
public void run() {
synchronized (lockA){
System.out.println(Thread.currentThread().getName() + "拿到" + lockA + "锁,尝试获取" + lockB + "锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (lockB){
System.out.println(Thread.currentThread().getName() + "拿到" + lockB + "锁,尝试获取" + lockA + "锁");
}
}
}
}
package com.hz.xhf;
public class DeadLockTest {
public static void main(String[] args) {
String lockA = "lockA";
String lockB = "lockB";
new Thread(new HoldLockThread(lockA, lockB), "ThreadA").start();
new Thread(new HoldLockThread(lockB, lockA), "ThreadB").start();
}
}
解决死锁方法
jps -l 定位进程号
jstack XXX 查错