zoukankan      html  css  js  c++  java
  • 写加锁但读没有加锁造成的脏读问题

    **
     * 对业务写方法加锁
     * 对业务读方法不加锁
     * 容易产生脏读问题 就是对写加锁但对读没有加锁,这样在写的过程中可能还没写完就被读了
     * 
     *
     */
    public class Demo {
     String name;
     double balance;
     
     public synchronized void set(String name, double balance){
      this.name = name;
      try {
       Thread.sleep(2 * 1000);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
      this.balance = balance;
     }
     
     public /*synchronized*/ double getBalance(String name){///*synchronized*/就是this对象与上面写加的锁是同一把 所以加了锁就能起到读写一体的作用
      return this.balance;
     }
     
     public static void main(String[] args) {
      Demo demo = new Demo();
      
      new Thread(()->demo.set("zhangsan",100.0)).start(); //JDK1.8新特性
      
      try {
       TimeUnit.SECONDS.sleep(1);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
      System.out.println(demo.getBalance("zhangsan"));
      
      try {
       TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
      System.out.println(demo.getBalance("zhangsan"));
     }
    }
    //结果是0.0 100.0  因为set方法中睡了两秒,所以第一次读是的double的默认值0.0
  • 相关阅读:
    ASP.NET面试题(二)
    iBatis.Net系列(四) iBatisNet API基础
    ibatisnet系列(一) 总览
    iBatisnet系列(二) 配置运行环境和日志处理
    HDU 1575 Tr A (矩阵乘法)
    HDU 连连看
    1504: ZZ的橱柜 (优先队列)
    离散化思想
    POJ 2777 Count Color (线段树)
    POJ 1823 Hotel (线段树)
  • 原文地址:https://www.cnblogs.com/wl889490/p/12805218.html
Copyright © 2011-2022 走看看