为什么死锁程序写出来,咋程序结果不容易死锁呢?
package day04;
class Test1 implements Runnable {
Object locka = new Object();
Object lockb = new Object();
private boolean flag = true;
Test1(boolean flag) {
this.flag = flag;
}
public void run() {
if (flag) {
while (true) {
synchronized (locka) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("if lock");
synchronized (lockb) {
System.out.println("if lock");
}
}
}
} else {
while (true) {
synchronized (lockb) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("else lock");
synchronized (locka) {
System.out.println("else lock");
}
}
}
}
}
}
public class DeadLockTest {
public static void main(String[] args) {
Thread t1 = new Thread(new Test1(true));
Thread t2 = new Thread(new Test1(false));
t1.start();
t2.start();
}
}
如果把Object locka = new Object();
Object lockb = new Object();
改成
static Object locka = new Object();
static Object lockb = new Object();
立马就死锁了,为啥?
难道静态的东西和在内存中new一个对象有什么区别? |