本帖最后由 潇湘溪语 于 2013-11-26 11:39 编辑
毕老师视频第12天,生产者与消费者的代码如下,但是产生了如下问题,请高人解决一下咯,多谢啦!
图片上传失真了,部分字迹如下:
class ProducerConsumerDemo//二个线程同时运行,同步机制,生产者和消费者
{
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();
}
}
class Res
{
private String name;
private int num = 1;
private boolean flag = false;
public synchronized void in(String name)
{
while(flag)
try
{
this.wait();
}
catch (Exception e)
{}
this.name = name+"--"+num++;
System.out.println(Thread.currentThread().getName()+"生产者"+this.name);
flag = true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)
try
{
this.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.in("商品");
}
}
}
class Con implements Runnable
{
private Res r;
Con(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
|
|