java,为什么thread.wait()不能在我的代码中工作

时间:2015-04-29 08:51:45

标签: java multithreading wait notify

我有一个剧本(Thread)循环打印几段文字,还有一个用于打印紧急文本的屏幕破解,当屏幕破解打印时,它应该首先等待剧本。在屏幕破解后打印所有文本,它将通知剧本,并且剧本开始打印。

Create table RealData_long as select * from RealData

输出显示' wait()'根本不工作,剧本继续打印。 screenbreak永远不会打印它的文本。 为什么?这里有什么不对?

我修改代码并且有效。

class ScreenPlay implements Runnable{

    public synchronized void notifys() throws InterruptedException {
      notify();
    }

    public synchronized void waits() throws InterruptedException {
      wait();
    }

    public void run(){
      for(int i=0; i<15; i++){   
          System.out.println(i);
          try{
            Thread.sleep(500); 
          }catch(InterruptedException e){
            e.printStackTrace();
          }
          if( i == 14 ){
              i = -1;
          }
      }
    }
}

class ScreenBreak implements Runnable{
  private ScreenPlay screenplay;

  public ScreenBreak(ScreenPlay screenplay){
    this.screenplay = screenplay;
  }

  public void run(){
    try{
      Thread.sleep(2000);
      screenplay.waits();
    }catch(InterruptedException e){
      e.printStackTrace();
    }
    for(int i=0; i<5; i++){
      System.out.println("@_" + i);
    }
    try{
      Thread.sleep(5000);
      screenplay.notifys();
    }catch(InterruptedException e){
      e.printStackTrace();
    }
  }

}

public class Waits {
    public static void main(String[] args) {

      ScreenPlay s = new ScreenPlay();
      ScreenBreak sb = new ScreenBreak(s);
      new Thread(s).start();
      new Thread(sb).start();

    }
}

1 个答案:

答案 0 :(得分:4)

ScreenBreak开始wait()时,没有人notify()。对notify()的唯一电话是ScreenBreak,但它永远不会到达wait()

建议:回到tutorial