关于synchronized的问题
首先我定义类PersonalInfo如下:
public class PersonalInfo {
private String name;
private String id;
private int count;
public PersonalInfo() {
name = "nobody ";
id = "N/A ";
}
public void setNameAndID(String name, String id) {
synchronized(this)
{
this.name = name;
this.id = id;
}
if(!checkNameAndIDEqual()) {
System.out.println(count +
") illegal name or ID..... ");
}
count++;
}
private boolean checkNameAndIDEqual() {
return (name.charAt(0) == id.charAt(0)) ?
true : false;
}
}
接着定义类PersonalInfoTest如下:
public class PersonalInfoTest {
public static void main(String[] args) {
final PersonalInfo person = new PersonalInfo();
// 假设会有两个线程可能更新person对象
Thread thread1 = new Thread(new Runnable() {
public void run() {
while(true)
person.setNameAndID( "Justin Lin ", "J.L ");
}
});