Java线程的同步习题

2022.01.25线程同步练习题

银行有一个账户。 有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打 印账户余额。

问题:该程序是否有安全问题,如果有,如何解决?

【提示】

1,明确哪些代码是多线程运行代码,须写入run()方法

2,明确什么是共享数据。

3,明确多线程运行代码中哪些语句是操作共享数据的。

拓展问题:可否实现两个储户交替存钱的操作

 

自己写的及存在的问题:

①由于是使用runnable接口的方式创建的多线程和,new的lock锁需声明为静态的

②使用+=和-=比较好

复制代码
package www.fancy.security;

import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private int balance;

    public Account(int balance) {
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

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

    public void savemoney(int money) {
        if (money > 0) {
            balance = balance + money;
        }
    }
}

class Customer implements Runnable {
    private Account account = new Account(0);
    private int money;
    private ReentrantLock lock = new ReentrantLock();
    
    public Customer(int money){
        this.money = money;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public Customer() {
        
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            lock.lock();
            try {
                if(money > 0){
                    account.savemoney(1000);
                    System.out.println(Thread.currentThread().getName()+"banlance:"+account.getBalance());
                    money = money-1000;
                }else {
                    return;

            }
            } finally {
                lock.unlock();
            }
        }

    }
}
复制代码

运行测试类代码:

复制代码
package www.fancy.security;

public class CustomerTest {
    public static void main(String[] args) {
        Customer c = new Customer(6000);


        Thread c1 = new Thread(c);
        c1.setName("客户1:");
        Thread c2 = new Thread(c);
        c2.setName("客户2:");

        c1.start();
        c2.start();
    }
}
复制代码

得出结果:

客户1:banlance:1000
客户1:banlance:2000
客户1:banlance:3000
客户2:banlance:4000
客户2:banlance:5000
客户2:banlance:6000

Process finished with exit code 0

如何实现交替存钱?

预计目标:

 

客户1:banlance:1000
客户2:banlance:2000
客户1:banlance:3000
客户2:banlance:4000
客户1:banlance:5000
客户2:banlance:6000

Process finished with exit code 0

 

线程通信~

 

posted @   Fancy[love]  阅读(62)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示