生产者消费者模型的JAVA简单实现
类别: JSP教程
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();
}
}
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();
}
}
- 上一篇: 完全掌握JAVA中的
- 下一篇: TOMCAT下JSP、SERVLET和JAVABEAN环境的
-= 资 源 教 程 =-
文 章 搜 索