当前位置:编程学习 > JSP >>

生产者消费者模型的Java简单实现

答案: 

package testjava.thread;

public class SellBuy {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Q q = new Q();
  new Thread(new Producer(q)).start();
  new Thread(new Comsumer(q)).start();
  
 }

}
class Producer implements Runnable
{
 Q q;
 public Producer(Q q)
 {
  this.q=q;
 }
 public void run()
 {
  int i=0;
  while(true)
  {
   if(i==0)
    q.put("zhangsan","male");
   else
    q.put("lisi","femail");
   i=(i+1)%2; 
  }   
 }
}
class Comsumer implements Runnable
{
 Q q;
 public Comsumer(Q q)
 {
  this.q=q;
 }
 public void run()
 {
  while(true)
  {
   q.get();
  }
 }
}
class Q
{
 String name="unknown";
 String 易做图="unkonwn";
 boolean bFull=false;
 public synchronized void put(String name,String 易做图)
 {
  if(bFull)
   try {wait();} catch (Exception e) {}
  this.name=name;
  try {Thread.sleep(1);} catch (Exception e) {}
  this.易做图=易做图;
  bFull=true;
  notify();
 }
 public synchronized void get()
 {
  if(!bFull)
   try {wait();} catch (Exception e) {} 
  System.out.println(name+":"+易做图);
  bFull=false;
  notify();
  
 }
}

上一个:完全掌握java中的包机制
下一个:JAVA 中 jar 文件的编写和应用

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,