Skip to content

Instantly share code, notes, and snippets.

@finkformatics
Last active April 9, 2016 13:49
Show Gist options
  • Save finkformatics/32e344a4c1febc69724d08a60c56064c to your computer and use it in GitHub Desktop.
Save finkformatics/32e344a4c1febc69724d08a60c56064c to your computer and use it in GitHub Desktop.
Race condition example
/**
* Race condition example
*
* Creates a high number of threads and lets each increase a static int variable.
*
* Result: In most cases, the variable's value isn't 10000 after the program's finished, but a bit below.
*/
public class RaceConditionExample {
static int 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
z++;
});
// 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