wait()方法中的问题

时间:2015-09-23 14:17:20

标签: java

package sample;

public class Wait2 {
  boolean flag = true;
  private long waitTime = 10;
  Object obj = new Object();
  public static void main(String args[]){
    final Wait2 wait = new Wait2();


  //Create two threads:
  Thread thread1 = new Thread() {
     public void run() {
       wait.A();
     }
  };

  Thread thread2 = new Thread() {
     public void run() {
       wait.B();
     }
  };

  //Start the downloads.
  thread1.start();
  thread2.start();

  }
  public synchronized void A(){
    waitAndSweep("A");
  }

  public synchronized void B(){
    waitAndSweep("B");
  }
  protected void waitAndSweep(final String caller)  {

    synchronized (obj) {
      while (!flag) { try {
        obj.wait();
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } }
    }
    flag = false;
      long waitTime = getWaitTime();  

      if (waitTime > 0)
        try {
          wait(waitTime);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      System.out.println(caller + waitTime ); 
      SomeWork();


  }
  private void SomeWork() {
    this.waitTime = this.waitTime  + 1;
    flag=true;
    synchronized (obj) {
      obj.notify();
    }


  }
  public long getWaitTime() {
    return waitTime;
  }
  public void setWaitTime(long waitTime) {
    this.waitTime = waitTime;
  }

}

在这里,我试图实现wait()和notify(),但行中有一些错误--->等待(waitTime),同时调试它卡在那里。如果我使用Thread.sleep(waitTime)而不是wait(waitTime)。它工作正常。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的考试目的是什么?

你对Sleep和Wait方法感到困惑。 等待可以通过从另一个进程调用Notify方法唤醒,而Sleep不能。

等待和通知必须发生在监视器对象上的同步块中,而睡眠不会发生。

你可能因为Notify方法从未被调用而被调用而被调用,而替换Wait by Sleep一切正常,因为你永远不会锁定你的线程但只是冻结它一点点。