美文网首页
Java-0026-Synchronized同步

Java-0026-Synchronized同步

作者: 云转水流 | 来源:发表于2016-08-05 11:54 被阅读22次

    2016.8.4

    在进行多线程操作时,对一些数据不进行同步的话,可能会产生一些奇奇怪怪的结果,其中可能会有非常严重的后果。

    账户类

    class BankAccount{
        public double balance=1000;
    }
    

    丈夫存钱

    class Husband extends Thread{
        BankAccount account;
        public Husband(BankAccount account){
            this.account=account;
        }
        public void run(){
            System.out.println("当前余额:"+account.balance);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.balance=account.balance+200;
            System.out.println("充值后余额:"+account.balance);
        }
    }
    

    妻子存钱

    class Wife extends Thread{
        BankAccount account;
        public Wife(BankAccount account){
            this.account=account;
        }
        public void run(){
            System.out.println("当前余额:"+account.balance);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.balance=account.balance+200;
            System.out.println("充值后余额:"+account.balance);
        }
    }
    

    执行

        public static void main(String[] args){
            BankAccount account=new BankAccount();
            Husband husband = new Husband(account);
            Wife wife = new Wife(account);
            husband.start();
            wife.start();
        }
    

    结果

    搜狗截图20160804210535.png
    搜狗截图20160804210647.png
    搜狗截图20160804210630.png
    搜狗截图20160804210601.png

    其中第1和第3种情况很严重,存的钱都变少了。


    现在我们将run方法修改,用synchronized拿到account对象锁

        public void run(){
            synchronized(account){
                System.out.println("当前余额:"+account.balance);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                account.balance=account.balance+200;
                System.out.println("充值后余额:"+account.balance);
            }
        }
    

    再运行,就不会产生错误了

    搜狗截图20160805114732.png

    相关文章

      网友评论

          本文标题:Java-0026-Synchronized同步

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