鑑於這種Java代碼:此多線程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
當主方法完成的價值?是2000還是2000以下?我低於2000.兩個線程如何同時從run()
調用getNumer()
或setNumber()
,因爲每個線程都是同步的?
感謝RajChola回答 – Vijay
你」歡迎。如果你對你的問題有一個答案,你應該選擇其中一個答案是正確的。 – Sridhar