/**
* Too many synchronization methods may cause deadlock
* @author Administrator
*
*/
public class SynDemo03 {
/**
* @param args
*/
public static void main(String[] args) {
Object g =new Object();
Object m = new Object();
Test t1 =new Test(g,m);
Test2 t2 = new Test2(g,m);
Thread proxy = new Thread(t1); // holds the same object gm
Thread proxy2 = new Thread(t2);// Hold the same object gm
proxy.start();
proxy2.start();
}
}
class Test implements Runnable{
Object goods ;
Object money ;
public Test(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized(goods){ // Give the goods first
try {
Thread.sleep(100);//Increase the time delay to build a deadlock condition
} catch (InterruptedException e) {
e.printStackTrace ();
}
synchronized(money){ // giving money
}
}
System.out.println("Give the money in one hand");
}
}
class Test2 implements Runnable{
Object goods ;
Object money ;
public Test2(Object goods, Object money) {
super();
this.goods = goods;
this.money = money;
}
@Override
public void run() {
while(true){
test();
}
}
public void test(){
synchronized(money){ // give money first
try {
Thread.sleep(100); // Increase time delay to build deadlock phenomenon
} catch (InterruptedException e) {
e.printStackTrace ();
}
synchronized(goods){// is giving goods
}
}
System.out.println("First-hand delivery");
}
}