title: How to cause an object wait for some milliseconds, then cancel the active wait during the waiting time?
body: <p>I tied to cause an object wait for a period. In this period, the object could be locked and can not process any command. And the wait activity could be cancelled during the waiting period. </p>
  
  <p>Firstly, I tried the following method, it's a simple way:</p>
  
  <pre><code>public void toWaiting(int waitingTime)
  {
      synchronized(this) // this is the reference for the current object
      {
          try {
              this.wait(waitingTime);
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
      }
  }
  </code></pre>
  
  <p>It works, the current object could be blocked for waiting, but I can't cancel this wait activity during the waiting time. </p>
  
  <p>So I tried to use Thread to deal with this problem. Putting the wait method in a thread, then cancel the waiting activity by call <strong>Thread.interrupt()</strong>. I have wrote the following codes:</p>
  
  <pre><code>public void toWaiting(int waitingTime) 
  {
      robotWaitTask waitingTask = new robotWaitTask(waitingTime);
      waitingTask.start();
  }
  
  // Generate a thread which could cause the object waiting for a interval
  class robotWaitTask extends Thread 
  {
      int waitingTime;
  
      public robotWaitTask(int waitingTime)
      {
          this.waitingTime = waitingTime;
      }
  
      public void run()
      {
          synchronized(this)
          {
              try {
                  this.wait(waitingTime);
              } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      }
  }
  </code></pre>
  
  <p>The above is not working because the current object is not blocked, unless I change <strong>waitingTask.start()</strong> to <strong>waitingTask.run()</strong> ( I don't know why, there is no Exception). I  know call the run method dose not causes a new Thread generating, it's just a directly calling. So if I use <strong>waitingTask.run()</strong> , then there is no thread could be cancelled by interrupt() method.</p>
  
  <p>How to solve my problem?</p>