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
  • 相关阅读:
    微软的十年之变
    如何在易受攻击的SSD上禁用硬件BitLocker加密
    Tech Summit 2018见闻:我们,MVP
    Tech Summit 2018见闻:IT之家读者捕捉铺路集团董事长玄隐
    Windows 10怎么了?
    循环队列
    模拟键盘事件
    模拟鼠标事件
    进程间通信——— 匿名管道
    进程间通信——— LPC
  • 原文地址:https://www.cnblogs.com/wl889490/p/12805218.html
Copyright © 2011-2022 走看看