【发布时间】:2017-12-06 17:47:26
【问题描述】:
我正在寻找死锁示例,偶然发现了这段代码:
package com.example.thread.deadlock._synchronized;
public class BankAccount {
double balance;
int id;
BankAccount(int id, double balance) {
this.id = id;
this.balance = balance;
}
void withdraw(double amount) {
// Wait to simulate io like database access ...
try {Thread.sleep(10l);} catch (InterruptedException e) {}
balance -= amount;
}
void deposit(double amount) {
// Wait to simulate io like database access ...
try {Thread.sleep(10l);} catch (InterruptedException e) {}
balance += amount;
}
static void transfer(BankAccount from, BankAccount to, double amount) {
synchronized(from) {
from.withdraw(amount);
synchronized(to) {
to.deposit(amount);
}
}
}
public static void main(String[] args) {
final BankAccount fooAccount = new BankAccount(1, 100d);
final BankAccount barAccount = new BankAccount(2, 100d);
new Thread() {
public void run() {
BankAccount.transfer(fooAccount, barAccount, 10d);
}
}.start();
new Thread() {
public void run() {
BankAccount.transfer(barAccount, fooAccount, 10d);
}
}.start();
}
}
您将如何更改transfer 方法以使其不会导致死锁?第一个想法是为所有帐户创建一个共享锁,但这当然会杀死所有并发。那么有没有一种好方法可以只锁定交易中涉及的两个账户而不影响其他账户?
【问题讨论】:
标签: java multithreading concurrency synchronized