//创建一个资源 提供两个线程访问
class Person
{
String name;
String sex;
boolean bl = true; //判断资源里边是否已经填充过的变量
}
//创建一个输出对象
class InputDemo implements Runnable
{
private boolean flag= true;//定义一个变量用来填充不一样的内容
Person p;
InputDemo(Person p)
{
this.p=p;
}
public void run()
{
while(true)
{
synchronized(p)
{
if(p.bl)
{
try{p.wait();}catch(InterruptedException e){}//异常抛出
}
if(flag)
{
p.name="小强";
p.sex ="男";
flag =false;
}
else
{
p.name="弱弱";
p.sex ="女";
flag = true;
}
p.bl = true;
p.notify();
}
}
}
}
//创建一个输出对象
class Output implements Runnable
{
Person p ;
Output(Person p)
{
this.p = p;
}
public void run()
{
while(true){
synchronized(p)
{
if(p.bl)
p.bl = false;
System.out.println("姓名:"+p.name+"性别:"+p.sex);
try{p.wait();}catch(InterruptedException e){}
p.notify();
}
}
}
}
class ThResource2
{
public static void main(String[] args)
{
Person p = new Person();
InputDemo in = new InputDemo(p);
Output out = new Output(p);
Thread t = new Thread(in);
Thread t1 = new Thread(out);
t.start();
t1.start();
}
} |
|