如题所示,o1和o2申明为静态对象就可产生死锁,那非静态为什么不可以?我所理解的静态对象:在内存空间只存在一份;如果申明非静态是不是Locklock1=newLock(1);Locklock2=newLock(2);lock1和lock2中都存在o1和o2?publicclassLockimplementsRunnableprivateintflag;publicLock(intflag){this.flag=flag;}//**?**staticObjecto1=newObject();staticObjecto2=newObject();publicstaticvoidmain(String[]args){Locklock1=newLock(1);Locklock2=newLock(2);newThread(lock1).start();newThread(lock2).start();}publicvoidrun(){System.out.println("flag="+flag);if(flag==1){synchronized(o1){System.out.println("已持有O1对象锁.");try{Thread.sleep(1000);}catch(InterruptedExceptione){e.printStackTrace();}synchronized(o2){System.out.println("持有O2对象锁");}}}elseif(flag==2){synchronized(o2){System.out.println("已持有O2对象锁.");try{Thread.sleep(1000);}catch(InterruptedExceptione){e.printStackTrace();}synchronized(o1){System.out.println("持有O1对象锁");}}}}}
添加回答
举报
0/150
提交
取消