銀行有一個(gè)賬戶
有兩個(gè)儲(chǔ)戶分別向同一個(gè)賬戶存3000元肋杖,每次存1000溉仑,存3次。每次存完打印賬戶余額状植。
分析:
1.是否是多線程問(wèn)題浊竟??是,兩個(gè)儲(chǔ)戶線程
2.是否有共享數(shù)據(jù)浅萧?有逐沙,賬戶(或賬戶余額)、
3.是否有線程安全問(wèn)題洼畅?有
4.需要考慮如何解決線程安全問(wèn)題吩案?同步機(jī)制:有三種方式
package atguigu.exer;
/**
* @author zzw
* @create 2022-06-07 9:51
*/
class Customer1 implements Runnable {
private double balance;
public Customer1(double balance) {
this.balance =balance;
}
// 存錢
? public synchronized void deposit(double amt) {
if (amt >0) {
balance +=amt;
try {
Thread.sleep(100);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +":當(dāng)前的余額為:" +balance);
}
}
@Override
? public void run() {
for (int i =0; i <5; i++) {
deposit(1000);
}
}
}
public class AccountTest1 {
public static void main(String[]args) {
Customer1 c1 =new Customer1(0);
Thread t1 =new Thread(c1);
Thread t2 =new Thread(c1);
Thread t3 =new Thread(c1);
t1.setName("甲");
t2.setName("乙");
t3.setName("丙");
t1.start();
t2.start();
t3.start();
}
}