//关于多线程件通信--生产者消费者的小程序。
class Res
{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name)
{
if(flag)
try{wait();}catch(Exception e){}//为什么在这儿被唤醒的|t2不用判断上面的语句,直接进入下一语句??????????
this.name=name+"---"+count++;//在这儿"name+"---"+count++"是怎么赋给this.name的???????????
System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
flag=true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"消费者"+this.name);
flag=false;
this.notify();
}
}
class Pro implements Runnable
{
private Res r;
Pro(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
r.set("---商品---");
x=(x+1)%2;
}
}
}
class Con implements Runnable
{
private Res r;
Con(Res r)
{
this.r=r;
}
public synchronized void run()
{
int x=0;
while(true)
{
r.out();
x=(x+1)%2;
}
}
}
public class ProConDemo
{
public static void main(String[] args)
{
Res r=new Res();
Pro p1=new Pro(r);
Con c1=new Con(r);
Thread t1=new Thread(p1);
Thread t2=new Thread(p1);
Thread t3=new Thread(c1);
Thread t4=new Thread(c1);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
|
|