How does this multithreaded java code work?
•
Java
In view of this, the 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 value of the number when the main method is completed? 2000 or less? I got less than 2000 How do two threads simultaneously call getnumber () or setnumber () from run (), because each thread is synchronized?
Solution
Consider carefully what will happen in the next section
account.setNumber(account.getNumber() + 1);
Although both methods are synchronized separately, the overall operation is not
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码