当前位置: 代码迷 >> Java相关 >> [讨论]请教关于线程的问题!!
  详细解决方案

[讨论]请教关于线程的问题!!

热度:113   发布时间:2007-09-24 22:37:24.0
[讨论]请教关于线程的问题!!


请大家帮帮我理解这个程序中,notify()和wait()的用法!!
class lianxi
{
public static void main(String []args)
{
Queue q=new Queue();
Producer p=new Producer(q);
Consumer c=new Consumer(q);
p.start();
c.start();
}
}
class Producer extends Thread
{
Queue q;
Producer(Queue q)
{
this.q=q;
}
public void run()
{
for(int i=0;i<10;i++)
{
q.put(i);
System.out.println("producer put"+i);
}
}
}
class Consumer extends Thread
{
Queue q;
Consumer(Queue q)
{
this.q=q;
}
public void run()
{
while(true)
{
System.out.println("Consumer get"+q.get());
}
}
}
class Queue
{
int value;
boolean bfull=false;
public synchronized void put(int i)
{
if(!bfull)
{
value=i;
bfull=true;
notify();
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public synchronized int get()
{
if(!bfull)
{
try
{
wait();
}
catch(Exception e)
{
e.printStackTrace();
}
}
bfull=false;
notify();
return value;
}
}


搜索更多相关的解决方案: 线程  

----------------解决方案--------------------------------------------------------
wait()就是把线程放入对象等待序列中。notify就是唤醒一个等待的线程
----------------解决方案--------------------------------------------------------
回复:(向着梦想加速)[讨论]请教关于线程的问题!!...

能不能解释一下,具体的唤醒和等待的过程啊!如果可以的话请帮帮忙!!
在此先谢谢了!!


----------------解决方案--------------------------------------------------------

队列满了put方法就wait,然后唤醒get方法。。get取完后也wait,同时唤醒put方法。。。就这样。。。


----------------解决方案--------------------------------------------------------
  相关解决方案