2016-07-02
1 Deadlock problem
Thread A now occupies resource 2 and needs to request resources 1
Thread B now occupies resource 1 and needs to request resources 2
Thread 2 Gets the resource 2
Thread 1 Gets the resource 1
Thread 3 Gets the resource 3
Thread 3 is waiting for resource 1
Thread 1 is waiting for resource 2
Thread 2 is waiting for resource 3
Package com.java1995; /** @author*/Publicclass Resource { String resourcename; Public Resource (String resourcename) { this. resourcename=resourcename; }}
Packagecom.java1995;/*** Thread class *@authorAdministrator **/ Public classMyThreadextendsthread{Resource R1; Resource R2; MyThread (Resource r1,resource r2,string name) {Super(name); This. r1=R1; This. r2=R2; } Public voidrun () {synchronized(R1) {System.out.println ( This. GetName () + "acquired" +r1.resourcename); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ( This. GetName () + "waiting" +r2.resourcename); synchronized(R2) {System.out.println ( This. GetName () + "acquired" +r2.resourcename); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } }}
Packagecom.java1995;/*** Test class *@authorAdministrator **/ Public classTest { Public Static voidMain (string[] args) {Resource rs1=NewResource ("Resource 1"); Resource rs2=NewResource ("Resource 2"); Resource Rs3=NewResource ("Resource 3"); MyThread T1=NewMyThread (Rs1,rs2, "Thread 1"); MyThread T2=NewMyThread (RS2,RS3, "Thread 2"); MyThread T3=NewMyThread (rs3,rs1, "Thread 3"); T1.start (); T2.start (); T3.start (); }}
Resources
[1] Java Easy Start Classic tutorial "full version"
Java Section 60th deadlock problem