黑马程序员技术交流社区
标题:
求助,这个代码哪里错了?
[打印本页]
作者:
trhthyj
时间:
2014-4-15 08:30
标题:
求助,这个代码哪里错了?
class Res
{
String name;
String sex;
boolean flag=false;
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run ()
{
int x=0;
while(true)
{
synchronized(r)
{
if(r.flag)
{
try
{
r.wait();
}
catch(Exception e)
{
}
}
if(x==0)
{
r.name="wangming";
r.sex="nan";
}
else
{
r.name="王明";
r.sex="男";
}
x=(x+1)%2;
r.flag=true;
r.notify();
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
{
try
{
r.wait();
}
catch(Exception e)
{
}
}
else
{
System.out.println(r.name+"........"+r.sex);
}
r.flag=false;
r.notify();
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
复制代码
为什么出来是这样子:
QQ截图20140415082939.png
(70.33 KB, 下载次数: 0)
下载附件
2014-4-15 08:29 上传
作者:
月光海
时间:
2014-4-15 09:07
else
{
System.out.println(r.name+"........"+r.sex);
}
这里有错,不要加else,如果输出线程在上面等待,等输入线程输入完成后,CPU切换到输出线程,由于输出语句在else里面,就不再输出了,就会又把flag改为false,这样中间就少了一句,这样就极有可能会出现两句同样的语句,而不是交替输出
作者:
王峰峰
时间:
2014-4-15 09:20
你这是一个“生产者与消费者”问题吧!
package wff.ithem;
class Res
{
String name;
String sex;
boolean flag=false;
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run ()
{
int x=0;
while(true)
{
synchronized(r)
{
if(r.flag) //当r.flag的值为true时,表时只能打印值
{
try
{
r.wait();
}
catch(Exception e)
{
}
}
if(x==0)
{
r.name="wangming";
r.sex="nan";
}
else
{
r.name="王明";
r.sex="男";
}
x=(x+1)%2; //表示x的值只能取0或着1
r.flag=true;
r.notify(); //唤醒等待的线程
}
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
{
try
{
r.wait();
}
catch(Exception e)
{
}
}
/**
* 错误在这里,这里不应该有else,
* 或着else时把下面三条语句都加进else中
*
*/
System.out.println(r.name+"........"+r.sex);
r.flag=false;
r.notify();
}
}
}
}
public class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2