1 Reply Latest reply: Dec 29, 2011 8:39 PM by jtahlborn RSS

    a question about Condition#await(long, timeunit)

    Johnny_hunter
      Hello, all:

      I am testing Condition#await(long, Timeunit).

      In my testing code there are two threads. Thread#1 acquires the lock first, releases it by calling condtion.await(50, TimeUnit.MILLISECONDS), and print sth.

      Thread#2 acquires the lock as soon as Thread#1 release it, but in its run(), it sleeps for 2000 millsec, during which time Thread#1's waiting should have expired and the code should have proceeded. Nevertheless, Thread#1 still suspend till Thread#2 run to its completion.

      My explaination is that the fact that Thread#1's waiting expired only means now it's mode switch to runnable, still it can't run until it re-acuquire the lock.

      Am I right?

      Thanks for your input

      The code is as below
      public class SyncTest {
           private Lock lock = new ReentrantLock();
           private Condition cond = lock.newCondition();
           
            class Task1 implements Runnable{
                
                public void run(){
                     if(lock.tryLock()){
                          try{
                               Thread.sleep(500);
                               cond.await(50,TimeUnit.MILLISECONDS);
                               System.out.println("Task1.");
                               
                          } catch (InterruptedException e) {
                               e.printStackTrace();
                          }
                          finally{
                               lock.unlock();
                          }
                     }
                }
           }
           
            class Task2 implements Runnable{
           
                public void run(){
                     boolean locked = false;
                     try {
                          locked = lock.tryLock(510, TimeUnit.MILLISECONDS);
                     } catch (InterruptedException e) {
                          e.printStackTrace();
                     }
                     if(locked){
                          try{
                               Thread.sleep(2000);
                               System.out.println("Task2.");
                               cond.signalAll();
                          } catch (InterruptedException e) {
                               e.printStackTrace();
                          }
                          finally{
                               lock.unlock();
                          }
                     }
                }
           }
           public static void main(String[] args){
                SyncTest st = new SyncTest();
                new Thread(st.new Task1()).start();
                new Thread(st.new Task2()).start();
                
           }
      }