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
  • 相关阅读:
    Servlet
    MySQL游标
    MySQL数据库的备份和还原
    MySQL安全管理
    MySQL存储过程
    MySQL联结——实现多表查询
    MySQL视图
    MySQL触发器
    asp.net core 读取连接字符串
    form表单提交前进行ajax验证
  • 原文地址:https://www.cnblogs.com/wl889490/p/12805218.html
Copyright © 2011-2022 走看看