日期:2014-05-20  浏览次数:20848 次

多线程,问题,大家帮我看看问题出在哪儿
class Test
{
public static void main(String args[])
{
Queen q=new Queen();
Producer pr=new Producer(q);
Consumer c=new Consumer(q);
pr.run();
c.run();

}
}
class Producer extends Thread
{
Queen q;
Producer(Queen q)
{
this.q=q;
}
public void run()
{
for(int i=0;i<=10;i++)
{
q.put(i);
}
}
}
class Consumer extends Thread
{
Queen q;
Consumer(Queen q)
{
this.q=q;
}
public void run()
{
while(true)
{
q.get();
}
}
}
class Queen
{
int value;
boolean bNull=true;
public synchronized void  put(int i)
{
if(bNull)
{
this.value=i;
bNull=false;
System.out.print("put:"+i);
notify();
}
try
{
wait();
}
catch (Exception e)
{
e.printStackTrace();
}

}
public synchronized void  get()
{
if(bNull)
{
try
{
wait();
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("get:"+value);
bNull=true;
notify();
}
}

------解决方案--------------------
pr.run();
c.run();

改为
pr.start();
c.start();

试试
------解决方案--------------------
引用:
pr.run();
c.run();

改为
pr.start();
c.start();

试试

如上:run()方法:将自定义的代码存储在run方法中,让线程运行
start()方法,启动线程,底层调用run()方法
pr.run();没有启动线程
------解决方案--------------------
多线程是用start来启动的