- java 的死锁有点像相对而行走在独木桥的人,占用当前资源,又等待着另一个资源,并且是多个任务互相占用;
代码案例:
public static void main(String[] args) {
final Object a = new Object();
final Object b = new Object();
Thread threadA = new Thread(new Runnable() {
public void run() {
synchronized (a) {
try {
System.out.println("now i in threadA-locka");
Thread.sleep(1000l);
synchronized (b) {
System.out.println("now i in threadA-lockb");
}
} catch (Exception e) {
// ignore
}
}
}
});
Thread threadB = new Thread(new Runnable() {
public void run() {
synchronized (b) {
try {
System.out.println("1");
Thread.sleep(1000l);
synchronized (a) {
System.out.println("2");
}
} catch (Exception e) {
// ignore
}
}
}
});
threadA.start();
threadB.start();
}
如果想要解决相关死锁的问题:
1 顺序执行
2 多个对象资源占用
3 lock 释放资源
网友评论