标签:
public class Test {
public static void main(String[] args) {
Message m = new Message();
new Thread(new SetMessage(m)).start();
new Thread(new GetMessage(m)).start();
}
}
class Message {
String name;
String sex;
}
class SetMessage implements Runnable {
private Message m;
public SetMessage(Message m) {
this.m = m;
}
int num = 0;
@Override
public void run() {
while (true) {
synchronized (m) {
if (num == 0) {
m.name = "Tom";
m.sex = "women";
} else {
m.name = "Jek";
m.sex = "men";
}
}
num = (num + 1) % 2;
}
}
}
class GetMessage implements Runnable {
private Message m;
public GetMessage(Message m) {
this.m = m;
}
@Override
public void run() {
while (true) {
synchronized (m) {
System.out.println(m.name + "\t" + m.sex);
}
}
}
}
标签:
原文地址:http://www.cnblogs.com/striver-lm/p/5720961.html