写了小程度测试java死锁。
我的疑问是:被锁定对象为什么要用static修饰呢?不用static就锁不住,不能出现死锁了。
未用static修饰的代码如下 :
public class TestDeadLock implements Runnable{
public int flag = 0;
Object o1 = new Object(); Object o2 = new Object();
public void run(){
System.out.println("flag=" + flag);
if(flag==1){
synchronized(o1){
System.out.println("1"+o2.hashCode());
try{
Thread.sleep(1500);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(o2){
//System.out.println("1"+o2.hashCode());
}
}
}
if(flag==0){
synchronized(o2){
System.out.println("1"+o2.hashCode());
try{
Thread.sleep(1500);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(o1){
//System.out.println("0"+o2.hashCode());
}
}
}
}
public static void main(String[] args){
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}
个人理解:不加static,TestDeadLock类在main方法中被new 了二次,td1和td2各自分别产生了o1,o2。run()方法去锁定时,也只能锁定td1和td2中各自的o1,o2对象
。加了 static后,TestDeadLock类无论new多少次,都只产生一个o1,一个o2对象。run()方法去锁定时,也就是锁定的唯一的,o1,o2.
测试方法:打印o1,o2的 hashcode();进行判断产生了几个o1,o2对象。
用static修饰的代码如下 :
public class TestDeadLock implements Runnable{
public int flag = 0;
static Object o1 = new Object(); static Object o2 = new Object();
public void run(){
System.out.println("flag=" + flag);
if(flag==1){
synchronized(o1){
System.out.println("1"+o2.hashCode());
try{
Thread.sleep(1500);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(o2){
//System.out.println("1"+o2.hashCode());
}
}
}
if(flag==0){
synchronized(o2){
System.out.println("1"+o2.hashCode());
try{
Thread.sleep(1500);
}catch(InterruptedException e){
e.printStackTrace();
}
synchronized(o1){
//System.out.println("0"+o2.hashCode());
}
}
}
}
public static void main(String[] args){
TestDeadLock td1 = new TestDeadLock();
TestDeadLock td2 = new TestDeadLock();
td1.flag = 1;
td2.flag = 0;
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
t1.start();
t2.start();
}
}