死锁DeadLock

死锁DeadLock
1、程序中难以发现和调试,坚决避免这种错误。

package thread;

public class DeadLock {
    public static void main(String[] args){
       //new两个object对象,作为参数
        Object a1 = new Object();
        Object a2 = new Object();

        Masthead01 s1 = new Masthead01(a1,a2);
        Masthead02 s2 = new Masthead02(a1,a2);
        //启动线程
        s1.start();
        s2.start();

    }
}
class Masthead01 extends Thread{
    Object a1 ;
    Object a2 ;

    public Masthead01(Object a1, Object a2) {
        this.a1 = a1;
        this.a2 = a2;
    }
    //重写run方法
    public void run(){
        synchronized (a1){
            synchronized (a2){}
        }

    }
}
class Masthead02 extends Thread{
    Object a1 ;
    Object a2 ;

    public Masthead02(Object a1, Object a2) {
        this.a1 = a1;
        this.a2 = a2;
    }
    public void run(){
        synchronized (a2){
            synchronized (a1){}
        }
    }
}

你可能感兴趣的:(Java进阶,java)