2012-03-29 45 views
0

鎖定等待/通知的優點是什麼?代碼非常相似。鎖定等待/通知的優點是什麼?

private Object full = new Object(); 
private Object empty = new Object(); 

private Object data = null; 

public static void main(String[] args) { 
    Test test = new Test(); 
    new Thread(test.new Producer()).start(); 
    new Thread(test.new Consumer()).start(); 
} 

public void push(Object d) { 
    synchronized (full) { 
     while (data != null) 
      try { 
       full.wait(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
    } 
    data = d; 
    System.out.println("push"); 
    synchronized (empty) { 
     if (data != null) 
      empty.notify(); 
    } 
} 

public Object pop() { 
    synchronized (empty) { 
     while (data == null) 
      try { 
       empty.wait(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
    } 
    Object o = data; 
    data = null; 
    System.out.println("pop"); 
    synchronized (full) { 
     if (data == null) 
      full.notify(); 
    } 
    return o; 
} 

class Producer implements Runnable { 
    public void run() { 
     while (true) { 
      push(new Object()); 
     } 
    } 
} 

class Consumer implements Runnable { 
    public void run() { 
     while (true) { 
      pop(); 
     } 
    } 
} 

private final ReentrantLock lock = new ReentrantLock(); 
private final Condition fullState = lock.newCondition(); 
private final Condition emptyState = lock.newCondition(); 

private Object data = null; 

public static void main(String[] args) { 
    Test test = new Test(); 
    new Thread(test.new Producer()).start(); 
    new Thread(test.new Consumer()).start(); 
} 

public void push(Object d) { 
    lock.lock(); 
    try { 
     while (data != null) 
      try { 
       fullState.await(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     data = d; 
     System.out.println("push"); 
     emptyState.signal(); 
    } finally { 
     lock.unlock(); 
    } 
} 

public Object pop() { 
    Object result; 
    lock.lock(); 
    try { 
     while (data == null) 
      try { 
       emptyState.await(); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     result = data; 
     data = null; 
     System.out.println("pop"); 
     fullState.signal(); 
    } finally { 
     lock.unlock(); 
    } 
    return result; 
} 

class Producer implements Runnable { 
    public void run() { 
     while (true) { 
      push(new Object()); 
     } 
    } 
} 

class Consumer implements Runnable { 
    public void run() { 
     while (true) { 
      pop(); 
     } 
    } 
} 
+0

我想'lock's更難理解錯了......我見過誰需要看文檔,他們得到一段代碼,與之前許多有經驗的程序員'wait' /'通知「對。 – dasblinkenlight 2012-03-29 13:51:41

回答