Note that there are some explanatory texts on larger screens.

plurals
  1. POJava synchronization not working as (I) expected
    primarykey
    data
    text
    <p>programmer mates. I was testing java threading capabilities with a very simple code (or at least it <em>seemed</em> simple). I have this class Account:</p> <pre><code>public class Account { protected double balance; public synchronized void withdraw(double value) { this.balance = this.balance - value; } public synchronized void deposit(double value) { this.balance = this.balance + value; } public synchronized double getBalance() { return this.balance; } } </code></pre> <p>And I have two threads: <code>Depositer</code>, that deposits $10 a thousand times:</p> <pre><code>public class Depositer extends Thread { protected Account account; public Depositer(Account a) { account = a; } @Override public void run() { for(int i = 0; i &lt; 1000; i++) { this.account.deposit(10); } } } </code></pre> <p>And <code>Withdrawer</code>, that withdraws $10 a thousand times:</p> <pre><code>public class Withdrawer extends Thread { protected Account account; public Withdrawer(Account a) { account = a; } @Override public void run() { for(int i = 0; i &lt; 1000; i++) { this.account.withdraw(10); } } } </code></pre> <p>This arrangement is executed by:</p> <pre><code>public class Main { public static void main(String[] args) { Account account = new Account(); Thread c1 = new Depositer(account); Thread c2 = new Withdrawer(account); c2.start(); c1.start(); System.out.println(account.getBalance()); } } </code></pre> <p>As the methods are sychronized, I just expected that the balance was always 0 at the end, but this not happens sometimes. And I sincerely cannot figure out why. Can someone see where is my fault?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload