Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding the race condition
    text
    copied!<p>Can someone explain where the race condition is in this piece of code. My lecturer set it and I don't fully understand how to spot them yet, or say why the result that is given happens.</p> <pre><code>public class SlowRace { public static void main(String args []) throws Exception { MyThread.count = 0 ; MyThread thread1 = new MyThread() ; thread1.name = "A" ; MyThread thread2 = new MyThread() ; thread2.name = "B" ; thread1.start() ; thread2.start() ; thread2.join() ; thread1.join() ; System.out.println("MyThread.count = " + MyThread.count) ; } } class MyThread extends Thread { volatile static int count ; String name ; public void run() { for(int i = 0 ; i &lt; 10 ; i++) { delay() ; int x = count ; System.out.println("Thread " + name + " read " + x) ; delay() ; count = x + 1; System.out.println("Thread " + name + " wrote " + (x + 1)) ; } } static void delay() { int delay = (int) (1000000000 * Math.random()) ; for(int i = 0 ; i &lt; delay ; i++) {} } } </code></pre> <p>The result that gets returned:</p> <pre><code>Thread A read 0 Thread A wrote 1 Thread B read 0 Thread A read 1 Thread B wrote 1 Thread A wrote 2 Thread B read 2 Thread A read 2 Thread B wrote 3 Thread A wrote 3 Thread B read 3 Thread A read 3 Thread B wrote 4 Thread A wrote 4 Thread B read 4 Thread A read 4 Thread B wrote 5 Thread A wrote 5 Thread B read 5 Thread A read 5 Thread B wrote 6 Thread A wrote 6 Thread B read 6 Thread A read 6 Thread B wrote 7 Thread A wrote 7 Thread B read 7 Thread A read 7 Thread B wrote 8 Thread A wrote 8 Thread B read 8 Thread A read 8 Thread B wrote 9 Thread A wrote 9 Thread B read 9 Thread A read 9 Thread B wrote 10 Thread A wrote 10 Thread B read 10 Thread B wrote 11 MyThread.count = 11 </code></pre>
 

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