java多线程场景1-模拟银行账户转账
public class BankTransferDemo {
public static void transfer(BankAccount from, BankAccount to, double amount) throws InterruptedException {
// 模拟网络延迟
TimeUnit.MICROSECONDS.sleep((long) (Math.random() * 100));
// 取款失败则直接结束
if(!from.withdraw(amount)){
return;
}
to.deposit(amount);
}
public static void main(String[] args) {
demo2();
}
/**
* 从不同账户往同一账户存钱
*/
public static void demo2(){
BankAccount account1 = new BankAccount("account1", 1000);
BankAccount account2 = new BankAccount("account2", 1000);
BankAccount account3 = new BankAccount("account3", 1000);
BankAccount account4 = new BankAccount("account4", 1000);
BankAccount account5 = new BankAccount("account5", 1000);
BankAccount account6 = new BankAccount("account6", 1000);
BankAccount account = new BankAccount("account", 0);
Thread thread1 = new Thread(() -> {
try {
transfer(account1, account, 200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread2 = new Thread(() -> {
try {
transfer(account2, account, 300);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread3 = new Thread(() -> {
try {
transfer(account3, account, 400);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread4 = new Thread(() -> {
try {
transfer(account4, account, 500);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread5 = new Thread(() -> {
try {
transfer(account5, account, 600);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
Thread thread6 = new Thread(() -> {
try {
transfer(account6, account, 1200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
thread6.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
thread5.join();
thread6.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 输出账户余额
System.out.printf("Final Balances: Account1: %.2f", account.getBalance());
}
/**
* 从同一账户多次取钱,存入同一账户
*/
public static void demo1(){
BankAccount account1 = new BankAccount("account1");
BankAccount account2 = new BankAccount("account2");
// 初始存款
account1.deposit(1000);
// 创建线程执行转载操作
Thread thread1 = new Thread(() -> {
try {
transfer(account1, account2, 200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
// 创建线程执行转载操作
Thread thread2 = new Thread(() -> {
try {
transfer(account1, account2, 100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// 输出账户余额
System.out.printf("Final Balances: Account1: %.2f, Account2: %.2f%n", account1.getBalance(), account2.getBalance());
}