
已解决问题
谷歌tcyk1314用户在2013.08.01提交了关于“三峡大坝J**a 线程通信”的提问,欢迎大家涌跃发表自己的观点。目前共有1个回答,最后更新于2024-11-05T21:18:52。classPro**cerimplementsRunnable{
Qq=**ll;
publicPro**cer(Qq)
{
this.q=q;
}
publicvoidrun()
{
inti=0;
while(true)
{
if(i==0)
{
q.put("张品","女");
}
else
{
q.put("郑爽","男");
}
i=(i+1)%2;
}
}
}
classConsumerimplementsRunnable
{
Qq=**ll;
publicConsumer(Qq)
{
this.q=q;
}
publicvoidrun()
{
while(true)
{
q.get();
}
}
}
classCommunication
{
publicstaticvoidmain(String[]args)
{
Qq=newQ();
newThread(newPro**cer(q)).start();
newThread(newConsumer(q)).start();
}
}
classQ
{
privateStringname;
privateString**;
privatebooleanbFull=false;
publicsynchronizedvoidput(Stringname,String**)
{
if(bFull)
{
try{this.wait();}catch(Exceptione){}
}
else
{
***.name=name;
***.**=**;
bFull=true;
this.notify();
}
}
publicsynchronizedvoidget()
{
if(bFull)
{
System.out.println(name+""+**);
bFull=false;
this.notify();
}
else
{
try{this.wait();}catch(Exceptione){}
}
}
}
为什么结果不是"张品","女"和"郑爽","男"这样循环出现的,而是一样出现几个,为什么没有实现线程间的通信?
还有如果我把put方法的else去掉又可以了,这是为什么?
谢谢希望大家能够帮助她。
详细问题描述及疑问:classPro**cerimplementsRunnable
{
Qq=**ll;
publicPro**cer(Qq)
{
this.q=q;
}
publicvoidrun()
{
inti=0;
while(true)
{
if(i==0)
{
q.put("张品","女");
}
else
{
q.put("郑爽","男");
}
i=(i+1)%2;
}
}
}
classConsumerimplementsRunnable
{
Qq=**ll;
publicConsumer(Qq)
{
this.q=q;
}
publicvoidrun()
{
while(true)
{
q.get();
}
}
}
classCommunication
{
publicstaticvoidmain(String[]args)
{
Qq=newQ();
newThread(newPro**cer(q)).start();
newThread(newConsumer(q)).start();
}
}
classQ
{
privateStringname;
privateString**;
privatebooleanbFull=false;
publicsynchronizedvoidput(Stringname,String**)
{
if(bFull)
{
try{this.wait();}catch(Exceptione){}
}
else
{
***.name=name;
***.**=**;
bFull=true;
this.notify();
}
}
publicsynchronizedvoidget()
{
if(bFull)
{
System.out.println(name+""+**);
bFull=false;
this.notify();
}
else
{
try{this.wait();}catch(Exceptione){}
}
}
}
为什么结果不是"张品","女"和"郑爽","男"这样循环出现的,而是一样出现几个,为什么没有实现线程间的通信?
还有如果我把put方法的else去掉又可以了,这是为什么?
谢谢期待您的答案,当代劳模,所有人都应该向你学习
!