美文网首页
脏读问题

脏读问题

作者: 好奇害死猫o | 来源:发表于2018-12-23 13:47 被阅读0次

    对业务写方法加锁,对业务读方法不加锁会出现脏读的情况

    import java.util.concurrent.TimeUnit;
    
    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"));
        }
    }
    

    运行结果如下:

    0.0
    100.0
    

    相关文章

      网友评论

          本文标题:脏读问题

          本文链接:https://www.haomeiwen.com/subject/hdzikqtx.html