package ThreadTest;
public class ThreadSafe {
public static void main(String[] args) {
Account act=new Account("act-001",10000);
Thread t1=new AccountThread(act);
Thread t2=new AccountThread(act);
t1.setName("取款线程1");
t2.setName("取款线程2");
t1.start();
t2.start();
}
}
class Account{
//银行账户类,actno是账户,balance是余额
private String actno;
private double balance;
public Account() {
//无参构造方法
}
public Account(String actno, double balance) {
//有参构造方法
super();
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) {
//取款方法,输入所要取款的数额money
double before=this.getBalance();//取款之前的余额
double after=before-money;//取款之后的余额
//在这里通过睡眠模拟网络延迟
try {
Thread.sleep(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setBalance(after);//更新余额
}
}
class AccountThread extends Thread{
//账户线程类,对于一个账户的不同线程操作,线程之间共享一个账户
private Account act;
public AccountThread(Account act) {
//通过构造方法选择账户对象
this.act = act;
}
public void run() {
//run方法表示取款操作,假设取款5000
double mony=5000;
act.withdraw(mony);
System.out.println("账户"+act.getActno()+"取款成功,余额为"+act.getBalance());
}
}
运行后输出为
账户act-001取款成功,余额为5000.0
账户act-001取款成功,余额为5000.0
显然不是线程安全的
必须要求取款方法只能有一个线程执行,不能并发,使用sunchronized关键字实现线程安全
package ThreadTest;
public class ThreadSafe {
public static void main(String[] args) {
Account act=new Account("act-001",10000);
Thread t1=new AccountThread(act);
Thread t2=new AccountThread(act);
t1.setName("取款线程1");
t2.setName("取款线程2");
t1.start();
t2.start();
}
}
class Account{
//银行账户类,actno是账户,balance是余额
private String actno;
private double balance;
public Account() {
//无参构造方法
}
public Account(String actno, double balance) {
//有参构造方法
super();
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) {
//使用线程同步机制,让这段代码只能有一个线程
synchronized(this) {
double before=this.getBalance();
double after=before-money;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setBalance(after);
}
}
}
class AccountThread extends Thread{
//账户线程类,对于一个账户的不同线程操作,线程之间共享一个账户
private Account act;
public AccountThread(Account act) {
//通过构造方法选择账户对象
this.act = act;
}
public void run() {
//run方法表示取款操作,假设取款5000
double mony=5000;
act.withdraw(mony);
System.out.println("账户"+act.getActno()+"取款成功,余额为"+act.getBalance());
}
}
输出为
账户act-001取款成功,余额为5000.0
账户act-001取款成功,余额为0.0