多线程练习---银行存款

银行存款问题

有两个人给一个银行账户存款,每个人分别存入3000元,一次存1000,分别存三次

package com.atguigu.exer;

import java.util.concurrent.locks.ReentrantLock;

class Account{
   private double banlance=0;
//存钱
    public void  subBanlance(double banlance) throws InterruptedException {
        Thread.sleep(1000);
        this.banlance += banlance;
    }

    public double getBanlance() {
        return banlance;
    }
}
//继承的方式
class Customer extends  Thread{
    private Account account;
    private static ReentrantLock lock=new ReentrantLock(true);//保证同一个锁
    public Customer(Account a){
        this.account=a;
    }

    @Override
    public void run() {
        for(int i=0;i<3;i++) {
            try {
                lock.lock();

                //synchronized (Customer.class) {
                try {
                    account.subBanlance(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "存入1000元,当前账户余额为" + account.getBanlance());
                // }
            }finally {
                lock.unlock();
            }
        }
    }
}
//接口的方式
class Customer2 implements Runnable{
    private Account account=new Account();
    private ReentrantLock lock=new ReentrantLock(true);
    @Override
    public void run() {
        for(int i=0;i<3;i++) {
            try {
                //synchronized (this) {
                lock.lock();
                try {
                    account.subBanlance(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "存入1000元,当前账户余额为:" + account.getBanlance());
                // }
            }finally {
                lock.unlock();
            }
        }
    }
}
public  class Bank {
    public static void main(String[] args) {
//        Account a= new Account();
//        Customer  t1=new Customer (a);
//        Customer  t2=new Customer (a);
//        t1.setName("存款人1");
//        t2.setName("存款人2");
//        t1.start();
//        t2.start();
        Customer2 customer2=new Customer2();
        Thread t1=new Thread(customer2);
        Thread t2=new Thread(customer2);
        t1.setName("存款人1");
        t2.setName("存款人2");
        t1.start();
        t2.start();
    }
}

你可能感兴趣的:(自学Java,多线程)