• 那是从何处传来的钟声呢?偶尔听到那钟声,平添一份喜悦与向往之情。

Java线程取款存款

后端 Nanait 12年前 (2012-08-03) 817次浏览 已收录 0个评论 扫描二维码

代码如下

  1. class Account {
  2.     int money = 100;
  3.     public int getMoney() {
  4.         return money;
  5.     }
  6.     public void add(int m) {
  7.         money += m;
  8.     }
  9.     public void desc(int m) {
  10.         money -= m;
  11.     }
  12. }
  13. //存钱
  14. class Deposit implements Runnable {
  15.     private Account account;
  16.     private int money;
  17.     public Deposit(Account account, int money) {
  18.         this.account = account;
  19.         this.money = money;
  20.     }
  21.     @Override
  22.     public void run() {
  23.         synchronized (Account.class) {
  24.             System.out.print(“当前余额:” + account.getMoney() + ” 存入:” + money);
  25.             account.add(money);
  26.             System.out.println(“,成功,余额为” + account.getMoney());
  27.         }
  28.     }
  29. }
  30. //取钱
  31. class Withdraw implements Runnable {
  32.     private Account account;
  33.     private int money;
  34.     public Withdraw(Account account, int money) {
  35.         this.account = account;
  36.         this.money = money;
  37.     }
  38.     @Override
  39.     public void run() {
  40.         synchronized (Account.class) {
  41.             System.out.print(“当前余额:” + account.getMoney() + ” 取出:” + money);
  42.             if (account.getMoney() >= money) {
  43.                 account.desc(money);
  44.                 System.out.println(“,成功,余额为” + account.getMoney());
  45.             } else {
  46.                 System.out.println(“,失败,余额不足”);
  47.             }
  48.         }
  49.     }
  50. }
  51. public class Demo8 {
  52.     public static void main(String args[]) throws InterruptedException {
  53.         Account account = new Account();
  54.         Thread t1 = new Thread(new Deposit(account, 100));
  55.         Thread t2 = new Thread(new Withdraw(account, 200));
  56.         Thread t3 = new Thread(new Deposit(account, 300));
  57.         Thread t4 = new Thread(new Withdraw(account, 400));
  58.         t1.start();
  59.         t2.start();
  60.         t3.start();
  61.         t4.start();
  62.     }
  63. }

运行结果图

Java 线程取款存款

 

注意这里的锁必须是唯一的,不能用 this,因为 this 的话指的是当前对象,这个两个不同类的线程对象,必须用一致的锁,比如都用   synchronized (“”) ,或者用某个类当做锁。


何处钟 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java 线程取款存款
喜欢 (0)
[15211539367@163.com]
分享 (0)

您必须 登录 才能发表评论!