/*两条线程同时操作一个资源
一个存入 一个获取 同时进行
*/
class Resource
{
private boolean flag = false;
private String name;
private String sex;
public synchronized void set(String name,String sex)
{
if(!flag)
try{this.wait();}catch(Exception e){}
this.name = name;
this.sex = sex;
flag = true;
notify();
}
public synchronized void out()
{
if(flag)
try{this.wait();}catch(Exception e){}
System.out.println(name+"......"+sex);
flag = false;
notify();
}
}
class Input implements Runnable
{
private Resource r;
Input(Resource r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
if (x == 0)
{
r.set("xiaohu","man");
}
else
{
r.set("wenjuan","girl");
}
x = (x+1)%2;
}
}
}
class Output implements Runnable
{
private Resource r;
Output(Resource r)
{
this.r = r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class TransformDemo
{
public static void main(String[] args)
{
Resource r = new Resource();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
}
}
上面是我写的代码 不知道哪里出错了 编译没问题 就是运行的时候结果不是交替执行的 而是一片一片的 不知道为啥
|