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

2008-02-23 09:33:06来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

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 sex="unkonwn";
boolean bFull=false;
public synchronized void put(String name,String sex)
{
if(bFull)
try {wait();} catch (Exception e) {}
this.name=name;
try {Thread.sleep(1);} catch (Exception e) {}
this.sex=sex;
bFull=true;
notify();
}
public synchronized void get()
{
if(!bFull)
try {wait();} catch (Exception e) {}
System.out.println(name ":" sex);
bFull=false;
notify();

}
}

上一篇: 快速Vsftpd配置手记
下一篇: 用Swing处理图片缩放和拖动!!!

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:JAgileSearch 1.3 alpha, a further step for me

下一篇:用Swing处理图片缩放和拖动!!!