package demo1;
/**
*
* Created by liudan on 2017/6/3.
*/
public class MyThread4 {
private String user = "liudan";
private String pwd = "123456";
private synchronized void setUserValue(String user, String pwd) {
this.user = user;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.pwd = pwd;
System.err.println("setValue 最终结果->:user = " + user + "\t" + "pwd = " + pwd);
}
private void getUserValue() {
System.err.println("getUserValue 设置值:user = " + this.user + "\t" + "pwd = " + this.pwd);
}
/**
* 对一个方法枷加锁,需要考虑功能业务的整体性,同时为set、get加锁,使用 synchronized 关键字,保证业务的原子性,不然则会出现业务的错误。
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
final MyThread4 tUser = new MyThread4();
Thread userThread = new Thread(new Runnable() {
@Override
public void run() {
tUser.setUserValue("testuser","111111");
}
});
userThread.start();
Thread.sleep(1000);
tUser.getUserValue();
}
}
- 正确结果输出:private synchronized void getUserValue()
- setValue 最终结果->:user = testuser pwd = 111111
getUserValue 设置值:user = testuser pwd = 111111
- 错误结果输出:private void getUserValue() 属于异步调用
- getUserValue 设置值:user = testuser pwd = 123456
setValue 最终结果->:user = testuser pwd = 111111