黑马程序员技术交流社区
标题:
线程同步没有输出的问题
[打印本页]
作者:
刘文飞
时间:
2012-11-17 14:25
标题:
线程同步没有输出的问题
本帖最后由 刘文飞 于 2012-11-17 15:51 编辑
class Resource
{
private String name;
private String sex;
private boolean flag;
public void setNameAndSex(String name,String sex)
{
this.name = name;
this.sex = sex;
}
public void setFlag(boolean flag)
{
this.flag = flag;
}
public boolean getFlag()
{
return this.flag;
}
public void print()
{
System.out.println(this.name + "-------" + this.sex);
}
}
class Input implements Runnable{
private Resource res;
public Input(Resource res)
{
this.res = res;
}
private int x = 0;
public void run()
{
while(true)
{
synchronized(res)
{
if(res.getFlag())
{
try{
res.wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
if(x == 0)
{
res.setNameAndSex("hezi","boy");
}
else
{
res.setNameAndSex("莉莉","女孩");
}
x = (x + 1)/2;
res.setFlag(true);
res.notify();
}
}
}
}
class Output implements Runnable
{
private Resource res;
public Output(Resource res)
{
this.res = res;
}
public void run()
{
while(true)
{
synchronized(res)
{
if(!res.getFlag())
{
try{
res.wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
res.print();
res.setFlag(false);
res.notify();
}
}
}
}
public class SynchronizedDemo01
{
public static void main(String[] args)
{
Input in = new Input(new Resource());
Output out = new Output(new Resource());
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
复制代码
编译没问题,运行也没有问题,就是没有输出啊。。
作者:
刘文飞
时间:
2012-11-17 15:51
睡了一觉醒来自个发现问题了,
Input in = new Input(new Resource());
Output out = new Output(new Resource());
这里两个匿名对象表示的不是同一个对象。。。。
两个线程都在那等着呢
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2