黑马程序员技术交流社区
标题:
为什么下面的程序发生只输出一行内容就停住了?
[打印本页]
作者:
方建平
时间:
2012-12-2 22:11
标题:
为什么下面的程序发生只输出一行内容就停住了?
上面程序结果只输出了一行
output----------------------name = Tom;sex = man
就卡住不动了,实在看不出什么原因啊!
import java.util.*;
class Resource
{
public String name = null;
public String sex = null;
public Boolean empty = true;
public Resource(String name,String sex)
{
this.name = name;
this.sex = sex;
this.empty = false;
}
}
class Inputer implements Runnable
{
Resource res = null;
Random rand = new Random(47);
public Inputer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
if(res.empty == true)
{
if((rand.nextInt(2) & 1) == 0 )
{
res.name = "Sheldon";
res.sex = "man";
}
else
{
res.name = "Avril";
res.sex = "woman";
}
res.empty = false;
System.out.println("input+++name = " + res.name + ";sex = " + res.sex);
}
}
}
}
class Outputer implements Runnable
{
Resource res = null;
public Outputer(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
if(res.empty == false)
{
System.out.println("output----------------------name = " + res.name + ";sex = " + res.sex);
res.empty = true;
}
}
}
}
public class InputOutputDemo
{
public static void main(String[] args)
{
Resource res = new Resource("Tom","man");
Thread t1 = new Thread(new Inputer(res));
Thread t2 = new Thread(new Outputer(res));
t1.start();
t2.start();
}
}
复制代码
作者:
黑马_张伟
时间:
2012-12-3 08:40
代码没有问题,我测试了。结果正确啊,一直输出的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2