资源描述:
《java并发编程(9):死锁(含代码)-编程开发技术》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、hva并发编程(9):死锁(含代码)-编程开发技术Java并发编程(9):死锁(含代码)原文出处:兰亭风雨当线程需要同时持冇多个锁时,冇可能产生死锁。考虑如下情形:线程A当前持有互斥所锁lockl,线程B当前持有互斥锁lock2o接下来,当线程A仍然持有lockl时,它试图获取lock2,因为线程B正持有lock2,因此线程A会阻塞等待线程B对lock2的释放。如果此时线程B在持有lock2的时候,也在试图获取lockl,因为线程A正持有lockl,因此线程B会阻塞等待A对]ockl的释放。二者都在等待对方所持有锁的释放,而二者却又都没释放自己所持有的锁,这时二者
2、便会一直阻塞下去。这种情形称为死锁。下而给出一个两个线程间产生死锁的示例,如下:publicclassDeadlockextendsObject{privateStringobjID;publicDeadlock(Stringid){objlD=id;}publicsynchronizedvoidcheckOther(Deadlockother){print(''enteringcheckOthcr(),z);try{Thread,sleep(2000);}catch(InterruptedExceptionx){}print(“incheckOther()-ab
3、outto"+"invokeother,action()'〃);//调用other对彖的action方法,由于该方法是同步方法,因此会试图获取other对彖的对彖锁other,action();print(z,leavingcheckOther()z,);}publicsynchronizedvoidaction(){print(〃enteringaction()z,);try{Thread,sleep(500);}catch(InterruptedExceptionx){}print(''leavingaction(),z);publicvoidprint(St
4、ringmsg){threadPrint(/,objID=z,+objID+〃一〃+msg);publicstaticvoidthreadPrint(Stringmsg){StringthreadName=Thread.currentThread().getNameO;System,out.println(threadName+〃:〃+msg);}publicstaticvoidmain(String[]args){finalDeadlockobjl=newDeadlock(〃obj1〃);finalDeadlockobj2=newDeadlock(〃obj2〃)
5、;RunnablerunA二newRunnable(){publicvoidrun(){objl.chcckOthcr(obj2);}};ThreadthreadA=newThread(runA,,zthreadA,z);thrcadA.start();try{Thread,sleep(200);}catch(InterruptedExceptionx){}RunnablerunB二newRunnable(){publicvoidrun(){obj2.checkOther(objl);}};ThreadthreadB=newThread(runB,z/thread
6、B/,);threadB.start();try{Thread,sleep(5000);}catch(IntcrruptcdExccptionx){}threadPrint(''finishedsleeping");threadPrint("abouttointerrupt()threadA");thrcadA.intcrrupt();try{Thread,sleep(1000);}catch(InterruptedExceptionx){}threadPrint(/zabouttointerrupt()threadBz/);threadB・interrupt()
7、;try{Thread,sleep(1000);}catch(InterruptedExceptionx){}threadPrint(/zdidthatbreakthedeadlock?");}运行结果如下:notfindthemainclass:定C:.IIVD0YSsysteB32cad.exe一javaDeadlockDeadlocks.Programwillexit.E:>javabreadA:tehreadB:DeadlockobjID=objlobjID=obj2巳ntering巳nteringcheckOtherOcheckOtherOoth
8、er.ac