zoukankan      html  css  js  c++  java
  • Java多线程之对写业务加锁,对读业务不加锁,会产生脏读

     1 import java.util.concurrent.TimeUnit;
     2 
     3 /**
     4  * 对写业务加锁
     5  * 对读业务不加锁
     6  * 脏读
     7  */
     8 public class Account {
     9 
    10     String name;
    11     double balance;
    12 
    13     public synchronized void set(String name, double balance) {
    14         this.name = name;
    15         try {
    16             Thread.sleep(2000); //写线程休眠两秒
    17         } catch (InterruptedException e) {
    18             e.printStackTrace();
    19         }
    20         this.balance = balance;
    21     }
    22 
    23     /**
    24      * 解决脏读在方法上加synchronized
    25      * @param name
    26      * @return
    27      */
    28     public /*synchronized*/ double getBalance(String name) {
    29         return this.balance;
    30     }
    31 
    32     public static void main(String[] args) {
    33 
    34         Account account = new Account();
    35         new Thread(() -> account.set("张三", 100.0)).start();
    36 
    37         try {
    38             TimeUnit.SECONDS.sleep(1); //读线程休眠一秒
    39         } catch (InterruptedException e) {
    40             e.printStackTrace();
    41         }
    42 
    43         System.out.println(account.getBalance("张三"));
    44 
    45         try {
    46             TimeUnit.SECONDS.sleep(2); //读线程休眠两秒
    47         } catch (InterruptedException e) {
    48             e.printStackTrace();
    49         }
    50 
    51         System.out.println(account.getBalance("张三"));
    52 
    53     }
    54 
    55 }
  • 相关阅读:
    DATASNAP远程方法返回TSTREAM正解
    DELPHI获取宽带IP
    DELPHI HMAC256
    JWT -- JSON WEB TOKEN
    UNIGUI集成HTML导航
    咏南WEB APP开发框架
    购买咏南中间件
    咏南中间件当作WEB SERVER使用方法
    咏南中间件增加WEBSOCKET支持
    iOS -- 设置label的自适应
  • 原文地址:https://www.cnblogs.com/mxh-java/p/12246451.html
Copyright © 2011-2022 走看看