Java解决线程操作共享数据安全问题的实例
题目:
银行有一个账户。
有两个储户分别向同一个账户存3000元,每次存1000,存3次。每次存完打印账户余额。
1. 继承方式实现
/*
1.是否涉及到多线程?(是,有两个储蓄户(两种方式来创建))
2.是否有共享数据? (有,账户余额)
3. 得考虑线程的同步(两种方法来处理线程的安全)
*/
class Account {
double balance;
public Account() {
}
//存钱
public synchronized void disposit(double amt) {
balance +=amt;
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+ ":" + balance);
}
}
class Customer extends Thread{
Account account;
public Customer(Account account) {
this.account = account;
}
public void run() {
for(int i = 0; i < 3; i++) {
account.disposit(1000);
}
}
}
public class TestAccount {
public static void main(String[] args) {
Account acct = new Account();
Customer c1 = new Customer(acct);
Customer c2 = new Customer(acct);
c1.setName("小红");
c2.setName("小黑");
c1.start();
c2.start();
}
}
1. 实现接口方式实现
class Account{
double balance;
public Account(){
}
public synchronized void disposit(double amt) {
balance +=amt;
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":" + balance);
}
}
class Customer implements Runnable{
Account account;
public Customer(Account account) {
this.account = account;
}
public void run() {
for (int i = 0; i < 3; i++) {
account.disposit(1000);
}
}
}
public class TestAccount {
public static void main(String[] args) {
Account account = new Account();
Customer c = new Customer(account);
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.setName("小黒");
t2.setName("小黄");
t1.start();
t2.start();
}
}