package com.thread.mythread.conn004;
public class DirtyRead {
private String username = "zhangsan";
private String password = "123";
public synchronized void setValue(String username,String password){
this.username = username;
try {
Thread.sleep(2000);
} catch (Exception e) {
// TODO: handle exception
}
this.password = password;
System.out.println("setValue :username=" + username + ",password=" + password);
}
public void getValue(){
System.out.println("getValue :username=" + this.username + ",password=" + this.password);
}
public static void main(String[] args) throws InterruptedException {
final DirtyRead dr = new DirtyRead();
Thread t1 = new Thread(new Runnable() {
public void run() {
dr.setValue("lisi", "456");
}
});
t1.start();
Thread.sleep(1000);
dr.getValue();
}
}
打印结果显示:
getValue :username=lisi,password=123
setValue :username=lisi,password=456
中间有两个线程,分别是主线程和t1线程。
1.主线程先执行;
2.执行到t1线程,主线程进入睡眠;
3.t1执行setValue方法,设置username=lisi,此时的password=123;
4.t1进入睡眠,主线程醒来
5.主线程调用getValue方法,打印getValue:username=lisi,password=123;
6.t1线程醒来,设置password=456;
7.t1线程打印setValue:username=lisi,password=456,完毕。
这里面跟上一篇提到的问题类似,都应用了一个对象dr,所以只能获取到一把锁,将两个方法都设置为线程同步synchronized。
public synchronized void getValue(){
System.out.println("getValue :username=" + this.username + ",password=" + this.password);
}
打印结果:
setValue :username=lisi,password=456
getValue :username=lisi,password=456
过程变为:
1.主线程执行;
2.执行到t1线程,主线程进入睡眠;
3.t1执行setValue方法,设置username=lisi,此时的password=123;
4.t1睡眠,主线程醒来接着等待;
5.t1醒来,设置password=456;
6.t1线程打印setValue:username=lisi,password=456;
7.主线程调用getValue方法,打印getValue:username=lisi,password=456,完毕。