死锁
概念:
- 过度同步,二个或二个以上的线程互相持有对方的锁,又不愿释放对方的锁。
产生原因:
- 资源不足
- 资源分配不当
- 进程推进的顺序不当
解决方法:
- 合理使用synchronized关键字
代码示例:
public class Runner implements Runnable{
private int flag;
private static Object object1 = new Object(),object2 = new Object();
public Runner(int flag) {
this.flag = flag;
}
public void run() {
if (flag == 1) {
System.out.println("a开始搞事情");
synchronized (object1) {
System.out.println("休息0.5秒后我要去搞b");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object2) {
System.out.println("我锁定了b");
}
}
}
if (flag == 0) {
System.out.println("b开始搞事情");
synchronized (object2) {
System.out.println("休息0.5秒后我要去搞a");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object1) {
System.out.println("我锁定了a");
}
}
}
System.out.println("Game Over!");
}
}
// 调用
public class DeadLockTest {
public static void main(String[] args) {
Runner r1 = new Runner(1);
Runner r2 = new Runner(0);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
// 输出
b开始搞事情
a开始搞事情
休息0.5秒后我要去搞a
休息0.5秒后我要去搞b