黑马程序员技术交流社区
标题:
貌似代码打错了,大家帮看看
[打印本页]
作者:
冯瀚冰
时间:
2012-4-8 10:51
标题:
貌似代码打错了,大家帮看看
class Resource
{
private String name;
private int count=1;
private boolean flag =false;
public synchronized void set(String name)
{
if(flag)
try{this.wait();}catch(Exception a){}
this.name=name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"...生产者...."+this.name);
flag=true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exception a){}
System.out.println(Thread.currentThread().getName()+"...消费者...."+this.name);
flag=false;
this.notify();
}
}
//---------------------------------
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.set("商品");
}
}
}
//----------------------------------
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
res.out();
}
}
//------------------------------------
class ProduceConsumerDemo
{
public static void main(String[] args)
{
Resource r =new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Thread t2=new Thread(con);
t1.start();
t2.start();
}
}
作者:
吴玉辉
时间:
2012-4-8 11:08
如图,你的t2线程没有放到循环里
p1.PNG
(16.67 KB, 下载次数: 40)
下载附件
2012-4-8 11:07 上传
作者:
冯瀚冰
时间:
2012-4-8 11:11
哦,谢谢
作者:
张卯
时间:
2012-4-8 11:26
最好不要用if,if只判断一次;
不过你这里只有一个生产者和消费者,没关系。
不要用notify(),要用notifyAll();
因为需要唤醒对方线程,只用notify,容易出现唤醒本方线程的情况,导致程序中的所有线程都等待。
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)//这里应该这样写
{
res.out();
}
}
}
作者:
pray
时间:
2014-4-26 05:21
难得一见的帖
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2