publicVar类:
package com.threades;
public class publicVar {
public String username;
public String password;
synchronized public void setValue(String username,String password){
try {
this.username=username;
Thread.sleep(2000);
this.password=password;
System.out.println("setValue method thread name :"+Thread.currentThread().getName()+"username= "+username+"password= "+password);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public void getValue(){
System.out.println("setValue method thread name :"+Thread.currentThread().getName()+"username= "+username+"password= "+password);
}
}
threadA类:
package com.threades;
public class threadA extends Thread{
private publicVar var;
public threadA(publicVar var){
super();
this.var=var;
}
public void run(){
super.run();
var.setValue("B", "BB");
}
}
run类:
package com.threades;
public class Run {
public static void main(String[] args) {
try {
publicVar var=new publicVar();
threadA A=new threadA(var);
A.setName("A");
A.start();
A.sleep(200);
var.getValue();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果为:
setValue method thread name :main username= Bpassword= null
setValue method thread name :A username= Bpassword= BB
若在publicVar中的getValue()方法前加synchronized关键字
synchronized public void getValue(){
System.out.println("setValue method
thread name :"+Thread.currentThread().getName()+"username=
"+username+"password= "+password);
}
运行结果则变成:
setValue method thread name :A username= Bpassword= BB
setValue method thread name :main username= Bpassword= BB
结论:当A调用对象的加入synchronized的方法时,A就获得了该方法的锁,其他线程则等A执行完毕再调用,但是B可以随时调用对象的其他非synchronized方法。
当B执行完非synchronized方法,若A未执行完成,则B需要等待A执行完synchronized方法之后B才执行synchronized方法,此时A已完成username以及password,就不存在读脏数据了。