死锁(面试常考)

来源:互联网 发布:matlab 矩阵色块图 编辑:程序博客网 时间:2024/06/05 01:13
//死锁之static关键字的作用 
public class TestDeadLock implements Runnable {
int flag = 0;
static Object t1 = new Object();//这个地方的static一定不能少  因为这里是成员变量的位置  如果不加static  那么每当你new一个TestDeadLock
static Object t2 = new Object();//对象出来时   就会同时在heap里面出现t1跟t2  这样根本锁不住 
public static void main(String[] args) {
TestDeadLock one = new TestDeadLock();//如果没有static  那么heap会有两队t1跟t2  达不到死锁的目的 
TestDeadLock two = new TestDeadLock();//画一下内存分布图就明白了  
Thread one1 = new Thread(one);
Thread two2 = new Thread(two);
one.flag = 1;
two.flag = 0;
one1.start();
two2.start();


}
public void run() {
System.out.println("flag=="+flag);
if(flag == 0) {
synchronized (t1) {
try {
Thread.sleep(5000);
   }  catch(Exception e) {
    return ;
      }
synchronized (t2) {
System.out.println("ok");
}
  }
  }

if(flag == 1) {
synchronized (t2) {
try {
Thread.sleep(5000);
} catch(Exception e) {
return ;
}
synchronized (t1) {
System.out.println("ok");
}
}
}

   }
}









0 0
原创粉丝点击