【发布时间】:2016-05-03 01:31:53
【问题描述】:
我目前正在学习 Java 同步。据我了解,同步实例方法在其对象上获取锁。
我的程序是一个有 50 个任务的地方,每个任务都有一个线程。每个任务都会向由帐户类创建的帐户对象添加一分钱。
Account 类有一个余额数据字段和一个同步的存款方法。这 50 个任务有一个指向同一个帐户对象的帐户字段(即共享帐户)。调用 run 后,每个任务都会调用 account.deposit 实例方法来存入 1 个单位。
我预计余额将以 50 个单位结束。令人惊讶的是,该帐户有时会以 50 或其他余额 14、48、33 等结束。
class JavaStudy {
public static void main(String[] args){
for (int j = 0; j < 10; j++) {
Account account = new Account();
ExecutorService executorPool = Executors.newFixedThreadPool(50);
for (int i = 0; i < 50; i++) {
executorPool.execute(new DepositTask(account));
}
executorPool.shutdown();
while(!executorPool.isShutdown()){
}
System.out.println(account.getBalance());
}
}
}
存款任务类!
class DepositTask implements Runnable {
private Account account;
DepositTask(Account account){
this.account = account;
}
@Override
public void run() {
account.deposit(1);
}
}
帐户类!
class Account {
private int balance = 0;
synchronized public void deposit(int amount){
int balance = this.balance + amount;
this.balance = balance;
}
String getBalance(){
return "Balance: " + balance;
}
}
据我了解,据我了解,一旦任务访问 account.deposit(1),帐户应该被锁定; .其他任务应该无法访问它,因为它们共享同一个对象!不知何故,这不会发生,我最终得到以下结果,
Balance: 20
Balance: 47
Balance: 50
Balance: 42
Balance: 27
Balance: 24
Balance: 50
Balance: 29
Balance: 13
Balance: 12
Process finished with exit code 0
有什么想法吗?
【问题讨论】:
-
"while(!executorPool.isShutdown()){}" - 有阻塞方法来实现等待终止!请不要这样做!
标签: java multithreading synchronization locking sharing