class Person
{
private String content;
private boolean flag = false ;
// 加入一个设置的同步方法
public synchronized void set(String content)
{
// 如果为绿灯则表示可以设置,否则等待:true
// 值是假,则表示要等待不能去设置,所以第一次不用等待
if(flag)
{
try
{
wait() ;
}
catch (Exception e)
{
}
}
this.content = content ;
// 设置完成之后,要改变灯
flag = true ;
notifyAll() ;
}
public synchronized String get()
{
if(!flag)
{
try
{
wait() ;
}
catch (Exception e)
{
}
}
String str =" --> "+this.content ;
// 如果为红灯,则表示可以取,否则等待:false
flag = false ;
notifyAll() ;
return str ;
}
};
class Pro implements Runnable
{
private Person per = null ;
public Pro(Person per)
{
this.per = per ;
}
public void run()
{
for(int i=0;i<100;i++)
{
if(i%2==0)
{
per.set("生产了") ;
}
else
{
per.set("吃完了") ;
}
}
}
};
class Cust implements Runnable
{
private Person per = null ;
public Cust(Person per)
{
this.per = per ;
}
public void run()
{
for(int i=0;i<100;i++)
{
System.out.println(per.get()) ;
}
}
} ;
public class Test19
{
public static void main(String args[])
{
Person per = new Person() ;
Pro p = new Pro(per) ;
Cust c = new Cust(per) ;
new Thread(p).start() ;
new Thread(c).start() ;
}
};
本文介绍了一个使用Java实现的生产者消费者模式案例。通过一个Person类作为共享资源,两个线程分别扮演生产者和消费者角色,进行数据的生产和消费。利用synchronized关键字和wait/notifyAll方法确保线程间的正确同步。
483

被折叠的 条评论
为什么被折叠?



