如题所示, o1和o2申明为静态对象就可产生死锁,那非静态为什么不可以? 我所理解的静态对象:在内存空间只存在一份; 如果申明非静态是不是Lock lock1 = new Lock(1);Lock lock2 = new Lock(2); lock1和lock2中都存在o1和o2?
public class Lock implements Runnable
private int flag;
public Lock(int flag) {
this.flag = flag;
}
// **?**
static Object o1 = new Object();
static Object o2 = new Object();
public static void main(String[] args) {
Lock lock1 = new Lock(1);
Lock lock2 = new Lock(2);
new Thread(lock1).start();
new Thread(lock2).start();
}
public void run() {
System.out.println("flag = " + flag);
if (flag == 1) {
synchronized (o1) {
System.out.println("已持有O1 对象锁.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println("持有O2 对象锁");
}
}
} else if (flag == 2) {
synchronized (o2) {
System.out.println("已持有O2 对象锁.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println("持有O1 对象锁");
}
}
}
}
}
添加回答
举报
0/150
提交
取消