/*
题目:存入一个人的姓名和性别后,输出这个人的姓名和性别。再存入再输出。
要求用多线程来操作,其实就是三个线程:一个主线程,再创建两个线程(输入一个线程、输出一个线程)
1,同步代码 synchronized 确保其安全性。
synchronized(this){}
synchronized(Input.class){}
多个代码块用同一个锁:Input.class
线程间通讯:
其实就是多个线程在操作同一个资源,
但是操作的动作不同
*/
class Res
{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(String name,String sex) //synchronized同步非静态函数
{
if(flag)
try{this.wait();}catch(Exception e){}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(name+"........"+sex);
flag=false;
this.notify();
}
}
class Input implements Runnable
{
private Res r;
Input(Res r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
r.set("mike","man");
else
r.set("丽丽","女女女女女");
x=(x+1)%2;
}
}
}
class Output implements Runnable
{
private Res r;
Output(Res r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r=new Res();
new Thread(new Input(r)).start();
new Thread(new Output(r)).start();
/*
Input in = new Input(r);
Output out =new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
*/
}
}