日期:2014-05-19  浏览次数:20709 次

java中的线程同步问题
问题一:为什么同步方法中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( );
  }
}


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