鉴于此 Java 代码:
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());
}
}
number
main 方法完成时的值是多少?是2000还是2000以下?我得到的数量少于 2000。鉴于每个线程都是同步的,如何同时调用getNumer()
或setNumber()
从两个线程调用?run()