课程: Java: Advanced Concepts for High-Performance Development
今天就学习课程吧!
今天就开通帐号,24,700 门业界名师课程任您挑!
Synchronized methods in Java - Java教程
课程: Java: Advanced Concepts for High-Performance Development
Synchronized methods in Java
- [Instructor] When you're working with threads, there are some things that can go wrong that is worth keeping an eye out for. So in this example, I have a class that represents a bank account. This class has a field called balance, which is set to 100, and then it has a method called debit, which takes an amount as an argument and then it subtracts that amount from the balance. And then there's a method called getBalance, which returns the balance. There's also a class called ATM, which has a withdraw method. So this method takes an account and an amount as arguments, and the first thing it does is it gets the balance of the bank account. Then it checks to see if minusing the amount from the balance would take the balance below zero. If it does, it prints out a message saying, "Transaction denied." If it doesn't, then it prints out a message saying, "Handling transaction," and then it calls the debit method on the…