日期:2014-05-20 浏览次数:20628 次
class Obj{
static Object obj1=new Object();
static Object obj2=new Object();
}
class Sisuo implements Runnable{
boolean flag=true;
public Sisuo(boolean flag){
this.flag=flag;
}
public void run(){
if(flag)
synchronized (Obj.obj1) {//死锁造成的原因是不是因为,一个synchronized拿着obj1变量,另一个synchronized拿着另一个拿着 obj2,这两个都想要对方的变量,可是变量已经在使用,
System.out.println("obj1----if");
synchronized (Obj.obj2) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("obj2----if");
}
}
else
synchronized (Obj.obj2) {
System.out.println("obj2----else");
synchronized (Obj.obj1) {
try {
Thread.sleep(10);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("obj1----else");
}
}
}
}
class Test{
public static void main(String[] args){
//Sisuo xiaosi=new Sisuo();
Thread t1=new Thread(new Sisuo(true));
Thread t2=new Thread(new Sisuo(false));
t1.start();
//Sisuo.flag=false;
t2.start();
}
}