欢迎来到我的博客

死锁

package demo.thread;

public class DeadLock {
   public static void main(String[] args) {
    Test a = new Test(true);
    Test b = new Test(false);
    Thread t1 = new Thread(a);
    Thread t2 = new Thread(b);
    t1.start();
    t2.start();
}
}


class Test implements Runnable{
    private boolean flag;
    Test(boolean flag) {
        this.flag = flag;
    }
    @Override
    public void run() {
         if(flag) {
             while(true) {
             synchronized (MyLock.lockA) {
                   System.out.println("if LockA");
                 synchronized (MyLock.lockB) {
                    System.out.println("if LockB");
                }
            }
             }
         } else {
             while(true) {
             synchronized (MyLock.lockB) {
                 System.out.println("else LockB");
                    synchronized (MyLock.lockA) {
                         System.out.println("else LockA");
                    }
                }
             }
         }        
    }
}

class MyLock {
    public static final Object lockA = new Object();
    public static final Object lockB = new Object(); 
}

 

posted @ 2017-10-16 19:57  Mr_Bean  阅读(119)  评论(0编辑  收藏  举报