Given this Java code:
class Account { private Integer number = 0; public synchronized void setNumber(Integer number) { this.number = number; } public synchronized Integer getNumber() { return number; } } class Client extends Thread { Account account; public Client(Account account) { this.account = account; } public void run() { for (int i = 1; i <= 1000; i++) { account.setNumber(account.getNumber() + 1); } } } public class Run { public static void main(String[] args) throws Exception { Account account = new Account(); Client one = new Client(account); Client two = new Client(account); one.start(); two.start(); one.join(); two.join(); System.out.println("Exiting main"); System.out.println("account number value: " +account.getNumber()); } }
What is the meaning numberwhen the main method is completed? Is it 2000 or less than 2000? I get less than 2000. How can two threads call getNumer()or setNumber()from run()simultaneously, given that each of them is synchronized?
number
getNumer()
setNumber()
run()
Think about what happens in the next section.
account.setNumber(account.getNumber() + 1);
Although both methods are separately synchronized, the operation as a whole is not.
2000, . , "set" "get" number , . , "" "increment".
:
number Thread1 Thread2 0 get => 0 - - - get => 0 - - incr => 1 1 - set => 1 - incr => 1 - 1 set => 1 -
, , , . , , set/get , .
, Account increment(), get/increment/set , 2000.
increment()