I'm new to Java and playing around with threads. I wrote this small program to check what happens when 3 threads are accessing an unsynchronized method:
class SharedValueHolder {
public static int globalCounter = 0;
public static void increment() {
globalCounter++;
}
}
class Incrementor implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
//reportValue();
SharedValueHolder.increment();
}
}
private void reportValue() {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " - " + SharedValueHolder.globalCounter);
}
}
public class ThreadTest {
public static void main(String... args) throws InterruptedException {
runTest();
}
private static void runTest() throws InterruptedException {
Thread thread1 = new Thread(new Incrementor());
Thread thread2 = new Thread(new Incrementor());
Thread thread3 = new Thread(new Incrementor());
thread1.start();
thread2.start();
thread3.start();
Thread.sleep(300);
System.out.println(SharedValueHolder.globalCounter);
}
}
Suprisingly, the result is almost always 15. Sometimes I do get a 14, but that's very rare.
Now if I uncomment the call to reportValue()
in Incrementor.run
I see something like this for example:
Thread-2 - 0
Thread-1 - 0
Thread-0 - 0
Thread-0 - 3
Thread-0 - 4
Thread-0 - 5
Thread-0 - 6
Thread-1 - 2
Thread-1 - 8
Thread-1 - 9
Thread-1 - 10
Thread-2 - 1
Thread-2 - 12
Thread-2 - 13
Thread-2 - 14
Which clearly shows that the threads "see" the same values at the same times, but still the result is correct. Could somebody explain to me how this works?