public class SimpleDeadlock implements Runnable{

static SimpleDeadlock sc1=null;
static SimpleDeadlock sc2=null;

    void access(SimpleDeadlock sc){

        if(Thread.currentThread().getName().equals("Thread1"))
            threadMethod1(sc);
        if(Thread.currentThread().getName().equals("Thread2"))
            threadMethod2(sc);
    }

    public synchronized void threadMethod1(SimpleDeadlock sc) {

        System.out.println(Thread.currentThread().getName()+": threadMethod1");
        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException ie){}
        sc.deadlock();
    }

    public synchronized void threadMethod2(SimpleDeadlock sc) {

        System.out.println(Thread.currentThread().getName()+": threadMethod2");
        try{
            Thread.sleep(1000);
        }
        catch(InterruptedException ie){}
        sc.deadlock();
    }

    synchronized void deadlock() {
        System.out.println("In deadlock...");
    }

    public void run(){
        if(Thread.currentThread().getName().equals("Thread1"))
            access(sc1);
        if(Thread.currentThread().getName().equals("Thread2"))
            access(sc2);
    }

    public static void main(String[] args) throws InterruptedException{

        sc1=new SimpleDeadlock();
        sc2=new SimpleDeadlock();
        Thread thread1=new Thread(sc1);
        Thread thread2=new Thread(sc2);
        thread1.setName("Thread1");
        thread2.setName("Thread2");
        thread1.start();
        thread2.start();
        Thread.sleep(10000);
        System.out.println(thread1.getName()+":"+thread1.getState());
        System.out.println(thread2.getName()+":"+thread2.getState());
    }
}


当我在运行方法中的访问方法中交换对象时,此示例发生在死锁中,因为Thread1等待Thread2完成,反之亦然。
但是,当它处于给定状态时,它不会陷入死锁。为什么?当thread1调用同步方法threadMethod1()时,对象sc1被锁定。然后,锁定对象sc1在该方法中如何调用另一个同步方法。

最佳答案

Java中的锁是可重入的。如果线程已经获取了锁并尝试再次获取它,则不会有任何问题。

10-08 19:28