线程安全-004-脏读

 例子程序:

package com.lhy.thread01;

public class DirtyRead {
    
    private String username = "lhy";
    private String password = "123";
    
    public synchronized void setValue(String username,String password){
        this.username = username;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.password = password;
        System.err.println(Thread.currentThread().getName()+":setValue最终结果:username = " +username +" , password = "+password);
    }
    //synchronized
    public  void getValue(){
        System.err.println(Thread.currentThread().getName()+":getValue方法得到:username = "+username+", password="+password);
    }
    
    public static void main(String[] args) throws Exception{
        final DirtyRead dr = new DirtyRead();
        
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                dr.setValue("zhangsan", "456");
            }
        },"t1");
        t1.start();
        Thread.sleep(1000);
        dr.getValue();
    }

}

打印结果:

线程安全-004-脏读

t1线程先对username设置值,将初始值 lhy 修改为 zhangsan ,然后睡眠1秒,此时 password还是初始值 123,所以主线程在1秒的时候读取到的username是修改后的zhangsan,password是初始值123,等到2秒时,t1线程将password修改为456,t1线程执行结束。打印username=zhangsan 、password=456。

要想保证读写业务的一致性,getValue也应该加上synchornized关键字。加上之后打印的结果就是我们预期的:

线程安全-004-脏读

 

线程安全-004-脏读

 

 欢迎关注个人公众号一起交流学习:

线程安全-004-脏读

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-07-29
  • 2021-07-12
  • 2021-12-30
  • 2021-09-30
猜你喜欢
  • 2021-04-23
  • 2022-12-23
  • 2021-06-16
  • 2021-08-23
  • 2021-08-26
  • 2021-06-20
相关资源
相似解决方案