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

📄 生产者-消费者.java

📁 生产者-消费者的JAVA小程序
💻 JAVA
字号:
class stack
{int sip=0;
 String data[]=new String[6];
 public synchronized void push(String str)
  {while(sip==data.length)
    {try
       {this.wait();
       }
      catch(InterruptedException e){}
    
    }
   this.notify();
   data[sip]=str;
   sip++;
  }
 public synchronized String pop()
  {while(sip==0)
   {try
       {this.wait();
        }
    catch(InterruptedException e){}
   }
  this.notify();
  sip--;
  return data[sip];
  }
}

class Producer implements Runnable
{stack stackOne;
 public Producer(stack s)
 {stackOne=s;
 }
 public void run()
 {String strTemp=null;
  for(int i=0;i<8;i++)
   {strTemp=String.valueOf(i+1);
    stackOne.push(strTemp);
    System.out.println("Produced:"+strTemp);
    try
     {Thread.sleep((int)(Math.random()*100));
     }catch(InterruptedException e){}
   }
  }
}

class Consumer implements Runnable
{stack stackOne;
 public Consumer(stack s)
 {stackOne=s;
 } 
 public void run()
 {String strTemp=null;
  for(int i=0;i<8;i++)
  {strTemp=stackOne.pop();
   System.out.println("Consumed:"+strTemp);
   try
     {Thread.sleep((int)(Math.random()*100));
     }catch(InterruptedException e){}
  }
 }
}

public class stackTest
{public static void main(String args[])
  {stack s1=new stack();
   Runnable producer=new Producer(s1);
   Runnable consumer=new Consumer(s1);
   Thread p=new Thread(producer);]
   Thread c=new Thread(consumer);
   p.start();
   c.start();
  }
}
    

⌨️ 快捷键说明

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