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());
}
}
当我在run方法中的access方法中交换对象时,此示例在死锁中发生,因为Thread1等待Thread2完成,反之亦然。 但是当它处于给定状态时,它不会陷入僵局。为什么?当thread1调用synchronized方法threadMethod1()时,对象sc1被锁定。那么在该方法中,锁定对象sc1如何调用另一个同步方法。
答案 0 :(得分:2)
Java中的锁是可重入的。如果一个线程已经获得一个锁并试图再次获取它,那么就不会有任何问题。