Created
November 20, 2013 16:42
-
-
Save NicMcPhee/7566471 to your computer and use it in GitHub Desktop.
A simple example that illustrates the existence of race conditions when using Java Threads. If you run this code on a multi-core box you're likely to get a lower count (potentially much lower) than you might naively expect.
This file contains hidden or 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
public class SimpleIncrement implements Runnable { | |
private static final int NUM_THREADS = 4; | |
private static final int NUM_INCREMENTS = 10000; | |
private static int count = 0; | |
public static void main(String[] args) throws InterruptedException { | |
Thread[] threads = new Thread[NUM_THREADS]; | |
for (int i=0; i<NUM_THREADS; ++i) { | |
threads[i] = new Thread(new SimpleIncrement()); | |
threads[i].start(); | |
} | |
for (int i=0; i<NUM_THREADS; ++i) { | |
threads[i].join(); | |
} | |
System.out.println("total count = " + count + " vs. expected = " + (NUM_THREADS * NUM_INCREMENTS)); | |
} | |
@Override | |
public void run() { | |
for (int i=0; i<NUM_INCREMENTS; ++i) { | |
++count; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment