class ProducecomsumerDemo
{
public static void main (Sting[] args)
{
Resource r=new Resource;
Produce pro=new Produce;
Consumer con=new Consumer;
Consumer t1=new Consumer(pro);
Consumer t2=new Consumer(pro);
Consumer t3=new Consumer(con);
Consumer t4=new Consumer(com);
t1,start;t2,start;t1,start;t1,start;
}
}
class Ressource
{
private sting name;
private int count=1;
private boolean flag=flase;
public synchronized void set (String name)
{
if(flag)
{
try(this.wait());
catch(Exception e){};
this.name=name+"......."+coun++;
system.out.println(this.getName()+"....生产者...."+this.name)
flag=ture;
this.notify();
}
}
}
public synchronized void out()
{
if(!flag)
{
try(this.wait());
catch(Exception e){};
syetem.out.println(this.getName+"....消费者...."+this.name)
flag=flase;
this.notify;
} }
class Prodncer implements Runable
{
private Resource res;
Producer (Resource res)
this.res=res;
public void run
{
while (true)
{res,set("...+商品...");
}
}
}
class Consumer implements Runable
{
private Resource res;
Producer (Resource res)
this.res=res;
public void run
{
while (true)
{
res,out();
}
}
}
在这个多线程中的同步函数中,如果t1进去执行了,出来的时候,flag变为ture,唤醒。这个时候如果t1还有执行权,去判断flag=true。等待。这个时候t2能进入同步函数中判断flag吗。
|