public class Res {
private String name;
private String sex;
boolean flag=true;//用来判断加载时是否有值
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public synchronized void set(String name,String sex){
if(flag){
try{this.wait();}catch(Exception e){System.out.println(e.getMessage());}
this.name=name;
this.sex=sex;
flag=false;
this.notify();
}
}
public synchronized void Out()
{
if(!flag){
try{this.wait();}catch(Exception e){System.out.println(e.getMessage());}
System.out.println(name+".............."+sex);
flag=true;
this.notify();
}
}
}
//资源输入类
public class input implements Runnable {
//初始化资源类
private Res r;
public input(Res r)
{
this.r=r;
}
@Override
public void run() {
int x=0;
while(true){
if(x==0)
r.set("张三", "男");
else
r.set("李四","女");
x=(x+1)%2;
}
}
}
//资源输出类
public class out implements Runnable {
private Res r;
public out(Res r)
{
this.r=r;
}
@Override
public void run() {
// 循环调用资源类输出方法
while(true){
r.Out();
}
}
}
public class OutInputDemo {
/**
*创建线程,时间Runnable接口
*使用同一个资源进行输入输出工作
*思路:
*1.定义资源类res
*2.里面有name和sex两个属性和一个out输出方法
*3.创建实现Runnable接口类input(输入类)初始化资源类同步代码
*4.创建实现Runnable接口类Out(输出类)调用资源类Out方法
*使用wati()等待和notify()唤醒机制实现输入输出切换功能
*/
public static void main(String[] args) {
//实例化资源类创建线程
Res r=new Res();
new Thread(new input(r)).start();
new Thread(new out(r)).start();
}
}
|