2013-05-02 60 views
1

我不熟悉线程和并发编程。我一直在寻找一个简单的片断,这将导致一个僵局,那就是:Java同步vs死锁示例

public class TestLock { 
    private static class fun { 
     int a,b; 

     void read() {System.out.println(a+b);} 
     void write(int a,int b) {this.a=a;this.b=b;} 
    } 

    public static void main (String[] args) throws java.lang.Exception { 
     final fun d1=new fun(); 
     final fun d2=new fun(); 

     Thread t1=new Thread() { 
      public void run() { 
       for(int i=0;i<5;i++) { 
        synchronized(d2) { 
         d2.read(); 
         try { 
          Thread.sleep(50); 
         } catch (Exception ex) { 
          ex.printStackTrace(); 
         } 
         synchronized(d1) { 
          d1.write(i, i); 
        } 
       } 
      } 
     }; 

     Thread t2=new Thread() { 
      public void run() { 
       for(int i=0;i<5;i++) { 
        synchronized(d1) { 
         d1.read(); 
         try { 
          Thread.sleep(50); 
         } catch (Exception ex) { 
          ex.printStackTrace(); 
         } 
         synchronized(d2) { 
          d2.write(i, i); 
         } 
        } 
       } 
      } 
     }; 
     t1.start(); 
     t2.start(); 
    } 
} 

现在我不知道我怎么会改变这个例子中,使用的ReentrantLock而不是同步的,但我不明白如何:是否有趣需要有一个ReentrantLock属性,以便有类似

Thread t1=new Thread() { 
    public void run() { 
     for(int i=0;i<5;i++) { 
      if(d2.lock.tryLock()) { 
        try {d1.read();Thread.sleep(50);} catch(Exception e) {e.printStackTrace();} finally {d1.lock.unlock();} 
         if(d2.lock.tryLock()) { 
          try {d2.write(i, i);} catch(Exception e) {e.printStackTrace();} finally {d2.lock.unlock();} 
         } 
        } 
       } 
      } 
     }; 

或者我完全错过了什么吗?

回答

1

使用ReentrantLocks转换示例实际上意味着使用两个锁:一个与d1关联,另一个与d2关联。

你可以通过调用lockX.lock()替换dX的同步块中的每个入口,并通过调用lockX.unlock()来从dX的同步块中退出。

使用tryLock()失败的目的,因为它返回而不是等待锁定无法获取。