死锁示例

class Test implements Runnable{
    private boolean flag;
    Test(boolean flag){
        this.flag = flag;
    }
    public void run(){
        if(flag){
            synchronized(Mylock.locka){
                System.out.println("if..locka..");
                synchronized(Mylock.lockb){
                    System.out.println("if..lockb..");
                }
            }
        }
        else{
            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();
}
class LockTest{
    public static void main(String[] args){
        Test x1 = new Test(true);
        Test x2 = new Test(false);
        Thread t1 = new Thread(x1);
        Thread t2 = new Thread(x2);
        t1.start();
        t2.start();
    }
}

 

posted @ 2017-11-18 16:09  想不出所以然丶  阅读(115)  评论(0)    收藏  举报