- public class DeadLockTest {
- public static void main(String[] args) {
- Thread t1 = new Thread(new Test(true));
- Thread t2 = new Thread(new Test(false));
- t1.start();
- t2.start();
- }
- }
- class MyLock
- {
- //static MyLock lock1=new MyLock();
- //static MyLock lock2=new MyLock();
- }
- class Test implements Runnable {
- MyLock lock1=new MyLock();//加static就会死锁
- MyLock lock2=new MyLock();//加static就会死锁
- private boolean flag;
- Object obj1 = new Object();
- Object obj2 = new Object();
- public Test(boolean flag) {
- this.flag = flag;
- }
- public void run() {
- if (flag) {
- while (true) {
- synchronized (lock1) {
- System.out.println("if lock1");
- synchronized (lock2) {
- System.out.println("if lock2");
- }
- }
- }
- } else {
- while (true) {
- synchronized (lock2) {
- System.out.println("else lock2");
- synchronized (lock1) {
- System.out.println("else lock1");
- }
- }
- }
- }
- }
- }
复制代码 我想问一下以上程序为什么在注释处加static才会产生死锁,不加static为什么不会产生死锁现象? |