java多线程中的死锁

产生死锁的原因:多个线程用到了多个锁,多个锁之间存在交叉关系,就有可能产生死锁。

下面是简单的死锁,下面代码中的死锁不是一定会产生。

package demo_1;

public class TestDeadLock {

    public static void main(String[] args) {
        
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();
        
        Thread t1 = new Thread(thread1);
        Thread t2 = new Thread(thread2);
        
        t1.start();
        System.out.println(234);
        t2.start();

    }

}

class MyLock{
    static Object obj1 = new Object();
    static Object obj2 = new Object();
}

class Thread1 implements Runnable{

    @Override
    public void run() {
        synchronized (MyLock.obj1) {
            System.out.println("lock obj1");
/*            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/
            synchronized (MyLock.obj2) {
                System.out.println("say1..obj2");
            }
        }
        
    }
    
}
class Thread2 implements Runnable{

    @Override
    public void run() {
        synchronized (MyLock.obj2) {
            System.out.println("lock obj2");
/*            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/
            synchronized (MyLock.obj1) {
                System.out.println("say..obj1");
            }
        }
        
    }
    
}

 

posted @ 2016-05-02 18:08  长不高  阅读(147)  评论(0编辑  收藏  举报