public class ThreadcommunicateSafe {
public static void main(String[] args) {
Info mess= new Info();
Input in = new Input(mess);
Output out = new Output(mess);
new Thread(in).start();
new Thread(out).start();
}
}
class Info{
String name;
String sex;
}
class Input implements Runnable{
Info info;
int x = 0;
public Input(Info info) {
this.info=info;
}
@Override
public void run() {
while (true) {
synchronized(info){
if (x==0) {
info.name = "demo";
info.sex = "man";
} else {
info.name = "莉莉";
info.sex = "女生";
}
x=(x+1)%2;
}
}
}
}
class Output implements Runnable{
Info info;
public Output(Info info) {
this.info=info;
}
public void run() {
while (true) {
synchronized(info){
System.out.println("名字:"+info.name+"__性别:"+info.sex);
}
}
}
}
/*
* 输出
名字:莉莉__性别:女生
名字:莉莉__性别:女生
名字:莉莉__性别:女生
名字:莉莉__性别:女生
名字:demo__性别:man
名字:demo__性别:man
名字:demo__性别:man
名字:demo__性别:man
名字:demo__性别:man
名字:demo__性别:man
名字:demo__性别:man
*/
转载于:https://blog.51cto.com/jiangzuun2014/1440600