解决不了我会死不瞑目!!!!
public class ThreadTest
{
public static void main (String [] args)
{
Resource res = new Resource ();
Pro aa = new Pro (res);
Con bb = new Con (res);
new Thread (aa).start();
new Thread (bb).start ();
}
}
class Resource
{
private String name;
private int count = 0;
boolean flag = false;
public void add (String name)
{
synchronized (this)
{
while (flag)
{
try
{
this.wait();
}
catch (Exception e)
{
return;
}
}
this.name = name+count++;
System.out.println ("产生"+this.name);
flag = true;
this.notifyAll();
}
}
public void get ()
{
synchronized (this)
{
while (!flag)
{
try
{
this.wait();
}
catch (Exception e)
{
return;
}
}
System.out.println ("消费"+this.name);
flag = false;
this.notifyAll();
}
}
}
class Pro implements Runnable
{
private Resource res;
public Pro(Resource res)
{
this.res = res;
}
public void run ()
{
while (true)
{
res.add("馒头");
}
}
}
class Con implements Runnable
{
private Resource res;
public Con(Resource res)
{
this.res = res;
}
public void run ()
{
while (true)
{
res.get();
}
}
}
运行出错,不知道什么原因。
------解决方案--------------------
把Con类名换掉,Con是系统关键字不能使用