⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 usewatinotify.java

📁 java经典的源代码 我非常喜欢这个源代码 对于编程很有好处
💻 JAVA
字号:
//useWaitNotify..Java
public class useWaitNofity {

  public static void main(String[] args) {
    A a=new A();
    producer p=new producer(a);
    consumer c=new consumer(a);
    p.start();
    c.start();
  }
}
class producer extends Thread{
  private A a;
  producer (A a){
    this.a=a;
  }
  public void run(){
    for(int i=0;i<5;i++){
      try{
        Thread.sleep((int)(Math.random()*1000));
      }
      catch(InterruptedException e){
      }
      a.setShare(i);
      System.out.println(i+"produced by producer.");
    }
    a.setIsMore(false);
  }
}
class A{
  private int n=-1;
  private boolean isMore=true;
  private boolean writeable=true;
  synchronized void setShare(int n){
    while(!writeable)
      try{
        wait();
      }
      catch(InterruptedException e){
      }
    this.n=n;
    writeable=false;
    notify();
  }
  synchronized int getShare(){
    while(writeable)
      try{
      wait();
      }
      catch(InterruptedException e){
    }
    writeable=true;
    notify();
    return n;
  }
  boolean isAnyMore(){
    return isMore;
  }
  void setIsMore(boolean b){
    isMore=b;
  }
}
class consumer extends Thread{
  private A a;
  consumer(A a){
    this.a=a;
  }
  public void run(){
    while(a.isAnyMore()){
      try{
        Thread.sleep((int)(Math.random()*1000));
      }
      catch(InterruptedException e){
      }
      System.out.println(a.getShare()+"consumed by consumer");
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -