zoukankan      html  css  js  c++  java
  • 线程--脏读问题

    1.概念:

    对业务写方法加锁,对业务读方法不加锁,容易产生脏读问题(dirtyRead)

    2.代码:

    public class Account {
        String name;
        double balance;
        
        public synchronized void set(String name, double balance) {
            this.name = name;
            
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            
            this.balance = balance;
        }
        
        public /*synchronized*/ double getBalance(String name) {
            return this.balance;
        }
        
        
        public static void main(String[] args) {
            Account a = new Account();
            new Thread(()->a.set("zhangsan", 100.0)).start();
            
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            System.out.println(a.getBalance("zhangsan"));
            
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            System.out.println(a.getBalance("zhangsan"));
        }
    }

  • 相关阅读:
    openwrt 的依赖找不到问题
    数据包与IPTABLE关系
    wifidog 配置中文说明
    Java 线程
    Java 集合
    IDEA配置Maven并创建web项目
    逻辑覆盖
    获得天气数据
    小程序项目文件介绍
    window 10 使用git
  • 原文地址:https://www.cnblogs.com/ganchuanpu/p/7795983.html
Copyright © 2011-2022 走看看