public class Thread001 {
class Res{
public String userName;
private char sex;
}
class InputThread extends Thread{
Res res;
public InputThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count=0;
while (true){
synchronized(res){
if(count==0){
res.userName="张胜军";
res.sex='男';
}else {
res.userName="小薇";
res.sex='女';
}
count=(count+1)%2;
}
}
}
}
class OutThread extends Thread {
Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true){
synchronized(res){
System.out.println(res.userName+","+res.sex);
}
}
}
}
public static void main(String[] args) {
new Thread001().start();
}
public void start(){
Res res=new Res();
//写的线程
new InputThread(res).start();
//读的线程
new OutThread(res).start();
//锁的对象是Res
}
}