以:用线程同步处理的方法编写程序演示生产者和消费者模型 为例
代码:
package zhuabao;
class Share
{
int contents;
boolean available=false;
public synchronized int get()
{
while(available==false)//对于进程,如果当前没有能够拿去的数据,处于停止状态
{
try {
wait();
}
catch(Exception e) {
}
}
available=false;//已经拿取过
notifyAll();//释放对象锁,通知等待的线程重新占有锁并运行
return contents;//得到内容
}
public synchronized void put(int value)
{
while(available==true)//记录的过程中,如果当前存放的数据没有被拿走,处于停止状态
{
try {
wait();
}
catch(Exception e) {
}
}
contents=value;//数据已经被拿走,放入新的数据
available=true;//有新的数据,可以获取
notifyAll();//释放对象锁,通知等待的线程重新占有锁并运行
}
}
//生产者
class Customer extends Thread
{
Share shared;//分享处理成员
int number;
public Customer(Share s,int number)
{
shared=s;
this.number=number;
}
public void run()//顾客捕获获得数据并输出
{
int value=0;
for(int i=0;i<10;i++)
{
value=shared.get();
System.out.println("消费者"+this.number+"得到的数据:"+value);
}
}
}
class Producer extends Thread
{
Share shared;//分享处理成员
int number;//记录序号
public Producer(Share s,int number)
{
shared=s;
this.number=number;
}
public void run()//生产者不断得到数据
{
for(int i=0;i<10;i++)
{
shared.put(i);
System.out.println("生产者"+this.number+"生产的数据:"+i);
}
try
{
sleep((int)Math.random()*100);
}
catch(Exception e) {
}
}
}
public class bao {
public static void main(String []args)
{
Share s=new Share();
Producer p=new Producer(s,1);
Customer c=new Customer(s,1);
p.start();
c.start();
}
}
运行结果:
在producer的run中插入断点
在消费者的run中插入断点
表明线程在运行的时候没有明显的先后关系(即使要求生产者在生产完10个数字之后说面0.1s),
并且因为有如下限制:
只有当前数据被取走之后才能生产下一个数据
消费者得到的数据一定是小于生产者生产的
关于sleep时间长短对于程序执行的影响
public class bao extends Thread
{
static int total=10;
int n;
String name;
public bao(int n,String name)
{
this.n=n;
this.name=name;
}
public void run()
{
try
{
System.out.println(name);
sleep(n);
total+=n;
System.out.println(total);
System.out.println(n);
}
catch(Exception e)
{
System.out.println();
}
}
public static void main(String[]args)
{
bao a1=new bao(3000,"A");
bao a2=new bao(1000,"B");
a1.start();
a2.start();
}
}
执行结果