• 实现一个类 支持100个线程同时向银行账户存入一元钱


    1. import java.util.concurrent.locks.Lock;
    2. import java.util.concurrent.locks.ReentrantLock;
    3. class BankAccount {
    4. private double balance;
    5. private Lock lock = new ReentrantLock();
    6. public BankAccount() {
    7. this.balance = 0.0;
    8. }
    9. public void deposit(double amount) {
    10. lock.lock();
    11. try {
    12. double currentBalance = balance;
    13. double newBalance = currentBalance + amount;
    14. balance = newBalance;
    15. } finally {
    16. lock.unlock();
    17. }
    18. }
    19. public void multiThreadDeposit(int numThreads, double amountPerThread) throws InterruptedException {
    20. Thread[] threads = new Thread[numThreads];
    21. for (int i = 0; i < numThreads; i++) {
    22. threads[i] = new Thread(() -> {
    23. deposit(amountPerThread);
    24. });
    25. threads[i].start();
    26. }
    27. for (int i = 0; i < numThreads; i++) {
    28. threads[i].join(); // 等待所有线程完成
    29. }
    30. }
    31. public double getBalance() {
    32. return balance;
    33. }
    34. }
    35. public class Main {
    36. public static void main(String[] args) throws InterruptedException {
    37. BankAccount bankAccount = new BankAccount();
    38. int numThreads = 100;
    39. double amountPerThread = 1.0;
    40. bankAccount.multiThreadDeposit(numThreads, amountPerThread);
    41. System.out.println("Final balance: " + bankAccount.getBalance());
    42. }
    43. }

    这个Java示例使用了ReentrantLock来实现线程同步,确保在多线程环境下对账户余额的访问是线程安全的。multiThreadDeposit方法启动了100个线程,并发执行存款操作。

    请注意,这只是一个简单的示例代码,用于演示如何在Java中实现多线程并发操作。在实际应用中,您可能需要更多的功能,如错误处理、日志记录等。此外,在真实的银行应用中,通常会使用更复杂的事务和安全性措施来确保数据的完整性和安全性。

  • 相关阅读:
    初识OpenGL (-)api(待扩展)
    halcon模板匹配和旋转矫正
    QSslSocket has not been declared
    Web应用接入OAuth2
    三栏布局,中间自适应
    面试题____Java小白找工作必须领悟的修仙秘籍(二)
    微信小程序显示流格式照片
    嵌入式程序架构的可行性建议
    jQuery使用的简单总结
    积加ERP与金蝶云星空对接集成日期范围报告查询打通销售出库新增
  • 原文地址:https://blog.csdn.net/mywaya2333/article/details/132814685