问题一:为什么同步方法中synchronized后面不用跟个(某个object),而同步代码块中却有,
问题二:下面这段代码,我是这么理解的:两个线程必定有一个先运行把。假设t1先运行,锁定了resource1然后进入了同步代码块,这时t1线程就会一直运行下去。直至同步代码块运行结束。也就是说在此期间t2根本没机会锁定resource2,怎么出现死锁啊,不知道我哪里理解有问题。请大侠指点。
public class Deadlock {
    public static void main(String[  ] args) {
        // These are the two resource objects we'll try to get locks for
        final Object resource1 = "resource1";
        final Object resource2 = "resource2";
        int a=0;
        // Here's the first thread.  It tries to lock resource1 then resource2
        Thread t1 = new Thread( ) {
                public void run( ) {
                    // Lock resource 1
                    synchronized(resource1) {
                        System.out.println("Thread 1: locked resource 1");
                        try { Thread.sleep(50); }
                        catch (InterruptedException e) {  }
                        // Now wait 'till we can get a lock on resource 2
                        synchronized(resource2) {
                         while(true){
                            System.out.println("Thread 1: locked resource 2");
                            try { Thread.sleep(10000); }
                            catch (InterruptedException e) {  }
                         }
                        }
                    }
                }
            };
        
        // Here's the second thread.  It tries to lock resource2 then resource1
        Thread t2 = new Thread( ) {
                public void run( ) {
                    // This thread locks resource 2 right away
                    synchronized(resource2) {
                        System.out.println("Thread 2: locked resource 2");
                        // Then it pauses, just like the first thread.
                        try { Thread.sleep(50); }
                        catch (InterruptedException e) {  }   
                   
                        synchronized(resource1) {
                            System.out.println("Thread 2: locked resource 1");
                        }
                    }
                }
            };
      
        t1.start( ); 
        t2.start( );
    }
}

解决方案 »

  1.   

    第一个 问题 ~~ 调用任何synchronized 方法时,对象就会被锁定,不可再调用那个对象的其他任何synchronized 方
    法,除非第一个方法完成了自己的工作,并解除锁定。
      

  2.   

    第一个问题:同步方法中synchronized针对class,同步代码块针对类的对象。第二个问题:
    你看看你的while(true){
      System.out.println("Thread 1: locked resource 2");
      try { Thread.sleep(10000); }
      catch (InterruptedException e) { }
      }while(true),不死锁才怪
      

  3.   

    第二个 假设第一个线程 先拿到resource1, 跑代码, 然后开始睡眠50秒。 然后这时候第二个线程拿到resource2的锁,因为这会第一个线程还在睡,第二个线程接着跑。跑着跑着他到了resource1的地方,他需要resource1的锁, 这会resouce1的锁在哪里? 还在第一个线程那。 第一个线程在干嘛。。他在等resource2..
      

  4.   


    一般synchronized的方法都会定义为static的