实体类——银行
public class Account {
//账户
private String actno;
//余额
private double balance;
private Object obj1 = new Object();
public Account() {
}
public Account(String actno, double balance) {
this.actno = actno;
this.balance = balance;
}
public String getActno() {
return actno;
}
public void setActno(String actno) {
this.actno = actno;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void withdraw(double money){
// Object obj2 = new Object();
synchronized(this) { //this指向当前对象Account,只同步需要共享的
// synchronized("a") { //字符串在常量池中,是所有都共有的
// synchronized(obj1) { //是this中的私有属性,作用和this一样
// synchronized(obj2) { //是在方法内声明的,是局部变量,线程不安全
//取款之前
double before = this.getBalance();
//取款之后
double after = before - money;
try {
Thread.sleep(1000*1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//更新余额
this.setBalance(after);
}
}
}
线程类,继承Thread,重写run方法,在run方法里边对金额进行操作
public class AccountThread extends Thread{
//两个线程共用一个账户对象
private Account act;
//通过构造方法传过来账户对象
public AccountThread(Account act) {
this.act = act;
}
@Override
public void run() {
//取款
double money = 5000;
act.withdraw(money);
System.out.println(Thread.currentThread().getName() +"对账户"+act.getActno()+"取款成功,余额"+act.getBalance());
}
}
测试类,模拟三个人的取款操作,t1和t2是同一个账户,使用一个共享资源,t3是单独的一个账户,不是同一个共享资源可以进行并发,不会出现线程安全的问题
public class Test {
public static void main(String[] args) {
Account account = new Account("001", 10000);
Thread t1 = new AccountThread(account);
Thread t2 = new AccountThread(account);
Account account2 = new Account("002", 10000);
Thread t3 = new AccountThread(account2);
t1.setName("t1");
t2.setName("t2");
t3.setName("t3");
t1.start();
t2.start();
t3.start();
}
}