class ThreadTest2
{
public static void main(String[] args)
{
Student st=new Student();
InPut input=new InPut(st);
OutPut output=new OutPut(st);
Thread in=new Thread(input);
Thread out=new Thread(output);
in.start();
out.start();
}
}
class Student
{
String name;
String sex;
Boolean flag=false;
}
class InPut implements Runnable
{
private Student st;
int x=0;
InPut(Student st)
{
this.st=st;
}
public void run()
{
while (true)
{
if (st.flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}else
{
synchronized(Student.class)
{
if (x==0)
{
st.name="zhansan";
st.sex="boy";
}else
{
st.name="lisi";
st.sex="girl";
}
x=(x+1)%2;
}
}
st.flag=true;
notify();
}
}
}
class OutPut implements Runnable
{
private Student st;
OutPut(Student st)
{
this.st=st;
}
public void run()
{
while (true)
{
if (!st.flag)
{
try
{
wait();
}
catch (Exception e)
{
}
}else
{
synchronized(Student.class)
{
System.out.println(st.name+"......"+st.sex);
}
}
st.flag=false;
notify();
}
}
} |