package cn.itcast.demo4;
/*
-
定义资源类,有2个成员变量
-
name,sex
-
同时有2个线程,对资源中的变量操作
-
1个对name,age赋值
-
2个对name,age做变量的输出打印
/
public class Resource {
public String name;
public String sex;
public boolean flag = false;
}
package cn.itcast.demo4;
/ -
开启输入线程和输出线程,实现赋值和打印值
*/
public class ThreadDemo{
public static void main(String[] args) {Resource r = new Resource(); Input in = new Input(r); Output out = new Output(r); Thread tin = new Thread(in); Thread tout = new Thread(out); tin.start(); tout.start();
}
}
package cn.itcast.demo4;
/* -
输入的线程,对资源对象Resource中成员变量赋值
-
一次赋值 张三,男
-
下一次赋值 lisi,nv
*/
public class Input implements Runnable {
private Resource r ;public Input(Resource r){
this.r = r;
}public void run() {
int i = 0 ;
while(true){
synchronized®{
//标记是true,等待
if(r.flag){
try{r.wait();}catch(Exception ex){}
}if(i%2==0){ r.name = "张三"; r.sex = "男"; }else{ r.name = "lisi"; r.sex = "nv"; } //将对方线程唤醒,标记改为true r.flag = true; r.notify(); } i++; }
}
}
package cn.itcast.demo4;
/*
-
输出线程,对资源对象Resource中成员变量,输出值
*/
public class Output implements Runnable {
private Resource r ;public Output(Resource r){
this.r = r;
}
public void run() {
while(true){
synchronized®{
//判断标记,是false,等待
if(!r.flag){
try{r.wait();}catch(Exception ex){}
}
System.out.println(r.name+"…"+r.sex);
//标记改成false,唤醒对方线程
r.flag = false;
r.notify();
}
}
}
}