一文读懂Java多线程背后的故事
public class BankAccount {
private int balance;
public synchronized void deposit(int amount) {
balance += amount;
}
public synchronized void withdraw(int amount) {
balance -= amount;
}
public synchronized int getBalance() {
return balance;
}
}
public class TransferTask implements Runnable {
private final BankAccount sourceAccount;
private final BankAccount targetAccount;
private final int amount;
public TransferTask(BankAccount sourceAccount, BankAccount targetAccount, int amount) {
this.sourceAccount = sourceAccount;
this.targetAccount = targetAccount;
this.amount = amount;
}
@Override
public void run() {
sourceAccount.withdraw(amount);
targetAccount.deposit(amount);
}
}
public class BankExample {
public static void main(String[] args) {
BankAccount account1 = new BankAccount();
BankAccount account2 = new BankAccount();
account1.deposit(1000);
TransferTask transferTask1 = new TransferTask(account1, account2, 500);
TransferTask transferTask2 = new TransferTask(account2, account1, 300);
Thread thread1 = new Thread(transferTask1);
Thread thread2 = new Thread(transferTask2);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Account 1 balance: " + account1.getBalance());
System.out.println("Account 2 balance: " + account2.getBalance());
}
}
- Web网站都变成灰色有哪些方法可以快速实现(解决方案)
- CPU双核处理器是什么意思?有什么好处?
- Windows server2022 网络负载平衡NLB的实现
- 值得长期不换的网名
- Realtek HD Audio Driver for DCH 瑞昱声卡驱动 6.0.9313.1 免费安装版 for win10/11
- 《战国无双2》(Sengoku Musou 2)中文智能安装免费版
- win10电脑上的剪切板在哪里?查看及打开Win10剪切板方法图解
- suffer软件(绘图工具) v8.0 官方安装免费版
- 剑灵活力值没了怎么办 几点更新
- 亲心卡170号怎么预约购买?阿里通信170号段亲心卡在线预约靓号方法