• 同一把锁


     1 public class SynchronizedClass extends Thread{
     2     private Account account;
     3     private double drawbalance;
     4     Object obj;
     5     public SynchronizedClass(String name,Account account,double drawbalance,Object obj){
     6         super(name);
     7         this.account=account;
     8         this.drawbalance=drawbalance;
     9         this.obj=obj;
    10         //start();
    11     }
    12     public void run(){
    13         try{sleep(100);}catch(Exception e){}
    14         synchronized(obj){
    15             if(drawbalance>account.getBalance()){
    16                 System.out.println("余额不足!");
    17             }else{
    18                 System.out.println("吐钱成功!");
    19                 try{
    20                     sleep(100);
    21                     System.out.println("取钱:"+drawbalance);
    22                     account.setBalance(account.getBalance()-drawbalance);
    23                     System.out.println("余额为:"+account.getBalance());
    24                 }catch(Exception e){
    25                     System.out.println(e);
    26                 }
    27             }
    28         }
    29         
    30         
    31     }
    32     public static void main(String[] args){
    33     
    34         Object o=new Object();//传到了两个线程中,保证了是同一个锁。
    35         Account a=new Account("刘腾",100000);
    36         new SynchronizedClass("A线程",a,100000,o).start();
    37         new SynchronizedClass("B线程",a,10000,o).start();
    38     }    
    39 }
    40 
    41 //账户
    42 class Account {
    43     private String name;
    44     private double balance;
    45     public Account(){}
    46     public Account(String name,double balance){
    47         this.name=name;
    48         this.balance=balance;
    49     }
    50     public void setName(String name){
    51         this.name=name;
    52     }
    53     public void setBalance(double balance){
    54         this.balance=balance;
    55     }
    56     public String getName(){
    57         return name;
    58     }
    59     public double getBalance(){
    60         return balance;
    61     }
    62     
    63     /*
    64     public boolean equals(Object obj){
    65         if(this==obj)return true;
    66         if(obj==null)return false;
    67         if(getClass()!=obj.getClass())return false;
    68         Account other =(Account) obj;
    69         if(other.name==name&&other.balance==balance)return true;
    70         else return false;
    71     }
    72     */
    73 }
  • 相关阅读:
    逼哥
    作业
    malloc的底层实现
    docker基本使用
    对mudo中noncopyable类的理解
    整理
    替换war包中的文件
    SpringMVC(1):SpringMVC入门
    MySQL(5):安装MySQL
    MySQL(4):卸载MySQL
  • 原文地址:https://www.cnblogs.com/teng-IT/p/4445558.html
Copyright © 2020-2023  润新知