多线程-脏读

对于对象的同步、异步的方法,设计程序的时候一定要考虑问题的整体,出现数据不一致就是一个经典的错误。

1.demo

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 + "	" + "pwd = " + pwd);
    }

    private  void getUserValue() {
        System.err.println("getUserValue 设置值:user = " + this.user + "	" + "pwd = " + this.pwd);
    }
    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();
    }
}

描述:set的方法加了 synchronized 关键字用到了同步,get方法获取没使用到 synchronized 关键字,最后到线程启动,线程一秒后,再次调用get方法,验证是否修可值。

运行结果:

    getUserValue 设置值:user = testuser pwd = 123456
    setValue 最终结果->:user = testuser pwd = 111111         

1.先输出get、后输出set;线程启动后先修改了 user 然后休眠了2秒:

Thread.sleep(2000);

,然后马上

Thread.sleep(1000);
这时的1秒有包含在2秒中,第1秒 get方法(无 synchronized )被调用了,第二秒才去调用set 方法。



2.demo
 private synchronized void getUserValue() {
        System.err.println("getUserValue 设置值:user = " + this.user + "	" + "pwd = " + this.pwd);
    }

运行结果:

    setValue 最终结果->:user = testuser pwd = 111111

    getUserValue 设置值:user = testuser pwd = 111111

1.验证了锁的释放,保障数据的真实。

2.对一个方法枷加锁,需要考虑功能业务的整体性,同时为set、get加锁,使用 synchronized 关键字,保证业务的原子性,不然则会出现业务的错误。

 
原文地址:https://www.cnblogs.com/xxt19970908/p/6965240.html