zoukankan      html  css  js  c++  java
  • 并发编程(二)—— 脏读

    一、概念

    对于对象的同步和异步的方法,我们在设计自己的程序的时候,一定要考虑问题的整体,不然就会出现数据不一致的错误,很经典的错误就是脏读(dirtyread)。

    二、示例【com.xxy.base.sync004】DirtyRead

     1 package com.xxy.base.sync004;
     2 
     3 public class DirtyRead {
     4     private String username = "admin";
     5     private String password = "123";
     6     
     7     public synchronized void setValue(String username, String password) {
     8         this.username = username;
     9         try {
    10             Thread.sleep(2000);
    11         } catch (InterruptedException e) {
    12             // TODO Auto-generated catch block
    13             e.printStackTrace();
    14         }
    15         this.password = password;
    16         System.out.println("setValue的最终结果:username = " + username + ", password = " + password);
    17     }
    18     
    19     /*synchronized*/
    20     public void getValue() {
    21         System.out.println("getValue方法得到:username = " + username + ", password = " + password);
    22     }
    23     
    24     public static void main(String[] args) {
    25         DirtyRead dr = new DirtyRead();
    26         Thread t1 = new Thread(new Runnable() {
    27             
    28             @Override
    29             public void run() {
    30                 dr.setValue("zhangsan", "456");
    31             }
    32         });
    33         t1.start();
    34         try {
    35             Thread.sleep(1000);
    36         } catch (InterruptedException e) {
    37             // TODO Auto-generated catch block
    38             e.printStackTrace();
    39         }
    40         
    41         dr.getValue();
    42     }
    43 }
    View Code

    三、示例总结:

    在我们对一个对象的方法加锁的时候,需要考虑业务的整体性,即为setValue/getValue方法同时加载synchronized同步关键字,保证业务(service)的原子性,不然会出现业务错误(也从侧面保证业务的一致性)。

  • 相关阅读:
    OleDbCommand 的用法
    递归求阶乘
    C#重写窗体的方法
    HDU 5229 ZCC loves strings 博弈
    HDU 5228 ZCC loves straight flush 暴力
    POJ 1330 Nearest Common Ancestors LCA
    HDU 5234 Happy birthday 01背包
    HDU 5233 Gunner II 离散化
    fast-IO
    HDU 5265 pog loves szh II 二分
  • 原文地址:https://www.cnblogs.com/upyang/p/13658981.html
Copyright © 2011-2022 走看看