Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 20th, 2012  |  syntax: None  |  size: 1.93 KB  |  hits: 5  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import java.util.concurrent.locks.Condition;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4. import java.util.logging.ConsoleHandler;
  5. import java.util.logging.Handler;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9. public class ReentrantLockTest implements Runnable {
  10.  
  11.     private final static Logger logger = Logger.getLogger(ReentrantLockTest.class.getName());
  12.     private ReentrantLock lock = new ReentrantLock();
  13.     private Condition cond = lock.newCondition();
  14.  
  15.     public ReentrantLock getLock() {
  16.         return lock;
  17.     }
  18.  
  19.     public Condition getCondition() {
  20.         return cond;
  21.     }
  22.  
  23.     public static void main(String[] args) throws InterruptedException {
  24.         ReentrantLockTest obj = new ReentrantLockTest();
  25.         logger.setLevel(Level.ALL);
  26.         logger.setUseParentHandlers(true);
  27.         Handler handler = new ConsoleHandler();
  28.         handler.setLevel(Level.ALL);
  29.         logger.addHandler(handler);
  30.  
  31.         Thread thread = new Thread(obj);
  32.         thread.start();
  33.         Thread.sleep(1000);
  34.  
  35.         Lock lock = obj.getLock();
  36.  
  37.  
  38.         lock.lock();
  39.         try {
  40.             Condition cond = obj.getCondition();
  41.             cond.signal();
  42.             logger.fine("main thread notify.");
  43.         } finally {
  44.             lock.unlock();
  45.         }
  46.  
  47.         thread.join();
  48.         logger.fine("thread joined.");
  49.     }
  50.  
  51.     @Override
  52.     public void run() {
  53.         lock.lock();
  54.         try {
  55.             lock.lock();
  56.             try {
  57.                 try {
  58.                     logger.fine("other thread wait condition notify.");
  59.                     cond.await();
  60.                     logger.fine("other thread notified condition.");
  61.                 } catch (InterruptedException ex) {
  62.                     // ignore interrupted exception.
  63.                 }
  64.             } finally {
  65.                 lock.unlock();
  66.             }
  67.         } finally {
  68.             lock.unlock();
  69.         }
  70.     }
  71. }