线程安全问题的解决:利用线程同步机制,采取对比方式对其内容进行理解与分析。 ——以java语言为例

public class Test {
    public static void main(String[] args) {
        //创建新的账户
        Account act=new Account("67529351994619423131",10000);
        //创建两个账户线程
        Thread t1=new AccountThread(act);
        Thread t2=new AccountThread(act);
        //对两个账户线程重命名
        t1.setName("t1线程");
        t2.setName("t2线程");
        //启动两个账户线程
        t1.start();
        t2.start();

    }
}在这里插入代码片
public class AccountThread extends Thread{
    private Account act;
    public AccountThread(Account act){
        this.act=act;
    }
    public void run(){
        double money=5000;
        act.withdraw(money);

        System.out.println(Thread.currentThread().getName()+"对账户"+act.getAct()+"取款成功,余额"+act.getBalance());
    }

}在这里插入代码片

//银行账户,不使用线程同步机制,出现线程安全问题

public class Account {
    private String act;
    private double balance;

    public Account() {
    }

    public Account(String act, double balance) {
        this.act = act;
        this.balance = balance;
    }

    public String getAct() {
        return act;
    }

    public void setAct(String act) {
        this.act = act;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
    public void withdraw(double money){
        //当前余额
        double before=this.getBalance();
        //取款后余额
        double after=before-money;
        //更新余额
        this.setBalance(after);


    }

}在这里插入代码片

效果图:可能出现多种不确定情况,原因:线程不同步。
在这里插入图片描述
在这里插入图片描述

//银行账户,使用线程同步机制,解决线程安全问题

public class Account {
    private String act;
    private double balance;

    public Account() {
    }

    public Account(String act, double balance) {
        this.act = act;
        this.balance = balance;
    }

    public String getAct() {
        return act;
    }

    public void setAct(String act) {
        this.act = act;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

        public void withdraw (double money){
        synchronized (this) {
            //当前余额
            double before = this.getBalance();
            //取款后余额
            double after = before - money;
            //延迟1秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //更新余额
            this.setBalance(after);

        }
    }


}在这里插入代码片

效果图:采取线程同步机制,只出现一种情况
在这里插入图片描述
最后两张图,清晰分析两者的不同之处:
是否采取线程同步机制,不同地方的对比:
未采取线程同步机制不同之地:
在这里插入图片描述

采取线程同步机制不同之地:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/immortalize/article/details/107747944