Last active
April 9, 2016 13:50
-
-
Save finkformatics/12825318f45e55ec2f3f502a0a49584a to your computer and use it in GitHub Desktop.
Race condition solved example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Race condition solved example | |
* | |
* The same as race condition example, but with a particular synchronized inc() method to increment z | |
* | |
* Result: After program termination z is always 10000 | |
*/ | |
public class RaceConditionSolvedExample { | |
static int z; | |
/** | |
* Method to increment z | |
*/ | |
synchronized static void inc() { | |
z++; | |
} | |
public static void main(String[] args) { | |
// Create array of 10000 threads | |
Thread[] threads = new Thread[10000]; | |
for (int i = 0; i < threads.length; i++) { | |
threads[i] = new Thread(() -> { | |
// Increment z, but synchronized | |
inc(); | |
}); | |
// Start the thread | |
threads[i].start(); | |
} | |
// Unnecessary here, but good to know: Waits for each thread to finish work | |
for (Thread t : threads) { | |
try { | |
t.join(); | |
} catch (InterruptedException e) { | |
} | |
} | |
System.out.println("The number is: " + z); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment