关于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 ");
}
});
Thread thread2 = new Thread(new Runnable() {
public void run() {
while(true)
person.setNameAndID( "Shang Hwang ", "S.H ");
}
});
System.out.println( "开始测试..... ");
thread1.start();
thread2.start();
}
}
我在PersonalInfo类中为
synchronized(this)
{
this.name = name;
this.id = id;
}
加了锁,所以应该不出现同步问题,但是运行后发现:
开始测试.....
6347892) illegal name or ID.....
7012526) illegal name or ID.....
13896265) illegal name or ID.....
18910649) illegal name or ID.....
20581877) illegal name or ID.....
23564456) illegal name or ID.....
25247335) illegal name or ID.....
32844828) illegal name or ID.....
34528749) illegal name or ID.....
35962576) illegal name or ID.....
请问这是怎么一回事??谢谢
[解决办法]
我也有这个问题,哪个高人来一下呀
[解决办法]
synchronized (this) {
this.name = name;
this.id = id;
if (!checkNameAndIDEqual()) {
System.out.println(count + ") illegal name or ID..... ");
}
}
把输出语句放到synchronized外面的话,不能保证判断的值跟上面的赋值是同一个,也就是复制保证同步,但是输出判断不同步,中间就乱了
[解决办法]
楼上的回答已经把楼主的问题说得很明白了。输出语句必须要和赋值语句在同一个方法块里面,否则不能保证判断时候的值和赋值时候的值是一致的