/*
生产者,消费者的例子
必须写while循环、notifyAll
*/
class Res
{
private String name;
private int count = 1;
private boolean flag = false;
public synchronized void set(String name)
{
while (flag)
{
try{wait();}catch(Exception e){}
this.name = name+count++;
System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
flag = true;
this.notifyAll();
}
}
public synchronized void show()
{
while (!flag)
{
try{wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"...消费者.........."+this.name);
flag = false;
this.notifyAll();
}
}
}
class Pro implements Runnable
{
private Res r;
Pro(Res r)
{
this.r = r;
}
public void run()
{
while (true)
{
r.set("商品");
}
}
}
class Con implements Runnable
{
private Res r;
Con(Res r)
{
this.r = r;
}
public void run()
{
while (true)
{
r.show();
}
}
}
class ProConDemo
{
public static void main(String[] args)
{
Res r = new Res();
Pro p = new Pro(r);
Con c = new Con(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(p);
Thread t3 = new Thread(c);
Thread t4 = new Thread(c);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
|
|